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
arithmetic subarrays
class Solution: def checkArithmeticSubarrays(self, nums: List[int], l: List[int], r: List[int]) -> List[bool]: ans = [] def find_diffs(arr): arr.sort() dif = [] for i in range(len(arr) - 1): dif.append(arr[i] - a...
https://leetcode.com/problems/arithmetic-subarrays/discuss/1231666/Python3-Brute-force
9
A sequence of numbers is called arithmetic if it consists of at least two elements, and the difference between every two consecutive elements is the same. More formally, a sequence s is arithmetic if and only if s[i+1] - s[i] == s[1] - s[0] for all valid i. For example, these are arithmetic sequences: 1, 3, 5, 7, 9 7, ...
[Python3] Brute force
468
arithmetic-subarrays
0.8
VoidCupboard
Medium
23,671
1,630
path with minimum effort
class Solution: def minimumEffortPath(self, heights: List[List[int]]) -> int: m, n = len(heights), len(heights[0]) queue = {(0, 0): 0} # (0, 0) maximum height so far seen = {(0, 0): 0} # (i, j) -> heights ans = inf while queue: newq = {} # ne...
https://leetcode.com/problems/path-with-minimum-effort/discuss/909094/Python3-bfs-and-Dijkstra
2
You are a hiker preparing for an upcoming hike. You are given heights, a 2D array of size rows x columns, where heights[row][col] represents the height of cell (row, col). You are situated in the top-left cell, (0, 0), and you hope to travel to the bottom-right cell, (rows-1, columns-1) (i.e., 0-indexed). You can move ...
[Python3] bfs & Dijkstra
219
path-with-minimum-effort
0.554
ye15
Medium
23,710
1,631
rank transform of a matrix
class Solution: def matrixRankTransform(self, matrix: List[List[int]]) -> List[List[int]]: m, n = len(matrix), len(matrix[0]) # dimension # mapping from value to index mp = {} for i in range(m): for j in range(n): mp.setdefault(matrix[i][j], []).append...
https://leetcode.com/problems/rank-transform-of-a-matrix/discuss/913790/Python3-UF
5
Given an m x n matrix, return a new matrix answer where answer[row][col] is the rank of matrix[row][col]. The rank is an integer that represents how large an element is compared to other elements. It is calculated using the following rules: The rank is an integer starting from 1. If two elements p and q are in the same...
[Python3] UF
465
rank-transform-of-a-matrix
0.41
ye15
Hard
23,728
1,632
sort array by increasing frequency
class Solution: def frequencySort(self, nums: List[int]) -> List[int]: return sorted(sorted(nums,reverse=1),key=nums.count)
https://leetcode.com/problems/sort-array-by-increasing-frequency/discuss/963292/Python-1-liner
22
Given an array of integers nums, sort the array in increasing order based on the frequency of the values. If multiple values have the same frequency, sort them in decreasing order. Return the sorted array. Example 1: Input: nums = [1,1,2,2,2,3] Output: [3,1,1,2,2,2] Explanation: '3' has a frequency of 1, '1' has a fr...
Python 1-liner
1,500
sort-array-by-increasing-frequency
0.687
lokeshsenthilkumar
Easy
23,730
1,636
widest vertical area between two points containing no points
class Solution: def maxWidthOfVerticalArea(self, points: List[List[int]]) -> int: l = [] for i in points: l.append(i[0]) a = 0 l.sort() for i in range(len(l)-1): if l[i+1] - l[i] > a: a = l[i+1] - l[i] return a
https://leetcode.com/problems/widest-vertical-area-between-two-points-containing-no-points/discuss/2806260/Python-or-Easy-Peasy-Code-or-O(n)
0
Given n points on a 2D plane where points[i] = [xi, yi], Return the widest vertical area between two points such that no points are inside the area. A vertical area is an area of fixed-width extending infinitely along the y-axis (i.e., infinite height). The widest vertical area is the one with the maximum width. Note t...
Python | Easy Peasy Code | O(n)
2
widest-vertical-area-between-two-points-containing-no-points
0.842
bhuvneshwar906
Medium
23,761
1,637
count substrings that differ by one character
class Solution: def countSubstrings(self, s: str, t: str) -> int: m, n = len(s), len(t) @cache def fn(i, j, k): """Return number of substrings ending at s[i] and t[j] with k=0/1 difference.""" if i < 0 or j < 0: return 0 if s[i] == t[j]: return...
https://leetcode.com/problems/count-substrings-that-differ-by-one-character/discuss/1101671/Python3-top-down-and-bottom-up-dp
5
Given two strings s and t, find the number of ways you can choose a non-empty substring of s and replace a single character by a different character such that the resulting substring is a substring of t. In other words, find the number of substrings in s that differ from some substring in t by exactly one character. Fo...
[Python3] top-down & bottom-up dp
303
count-substrings-that-differ-by-one-character
0.714
ye15
Medium
23,779
1,638
number of ways to form a target string given a dictionary
class Solution: def numWays(self, words: List[str], target: str) -> int: freq = [defaultdict(int) for _ in range(len(words[0]))] for word in words: for i, c in enumerate(word): freq[i][c] += 1 @cache def fn(i, k): """Return number o...
https://leetcode.com/problems/number-of-ways-to-form-a-target-string-given-a-dictionary/discuss/1101522/Python3-top-down-dp
2
You are given a list of strings of the same length words and a string target. Your task is to form target using the given words under the following rules: target should be formed from left to right. To form the ith character (0-indexed) of target, you can choose the kth character of the jth string in words if target[i]...
[Python3] top-down dp
169
number-of-ways-to-form-a-target-string-given-a-dictionary
0.429
ye15
Hard
23,784
1,639
check array formation through concatenation
class Solution: def canFormArray(self, arr: List[int], pieces: List[List[int]]) -> bool: mp = {x[0]: x for x in pieces} i = 0 while i < len(arr): if (x := arr[i]) not in mp or mp[x] != arr[i:i+len(mp[x])]: return False i += len(mp[x]) return True
https://leetcode.com/problems/check-array-formation-through-concatenation/discuss/918382/Python3-2-line-O(N)
9
You are given an array of distinct integers arr and an array of integer arrays pieces, where the integers in pieces are distinct. Your goal is to form arr by concatenating the arrays in pieces in any order. However, you are not allowed to reorder the integers in each array pieces[i]. Return true if it is possible to fo...
[Python3] 2-line O(N)
705
check-array-formation-through-concatenation
0.561
ye15
Easy
23,790
1,640
count sorted vowel strings
class Solution: def countVowelStrings(self, n: int) -> int: dp = [[0] * 6 for _ in range(n+1)] for i in range(1, 6): dp[1][i] = i for i in range(2, n+1): dp[i][1]=1 for j in range(2, 6): dp[i][j] = dp[i][j-1] + dp[i-1][j] ...
https://leetcode.com/problems/count-sorted-vowel-strings/discuss/2027288/Python-4-approaches-(DP-Maths)
45
Given an integer n, return the number of strings of length n that consist only of vowels (a, e, i, o, u) and are lexicographically sorted. A string s is lexicographically sorted if for all valid i, s[i] is the same as or comes before s[i+1] in the alphabet. Example 1: Input: n = 1 Output: 5 Explanation: The 5 sorted ...
✅ Python 4 approaches (DP, Maths)
3,200
count-sorted-vowel-strings
0.772
constantine786
Medium
23,816
1,641
furthest building you can reach
class Solution: def furthestBuilding(self, heights: List[int], bricks: int, ladders: int) -> int: # prepare: use a min heap to store each difference(climb) between two contiguous buildings # strategy: use the ladders for the longest climbs and the bricks for the shortest climbs min_...
https://leetcode.com/problems/furthest-building-you-can-reach/discuss/2176666/Python-or-Min-Heap-or-With-Explanation-or-Easy-to-Understand
32
You are given an integer array heights representing the heights of buildings, some bricks, and some ladders. You start your journey from building 0 and move to the next building by possibly using bricks or ladders. While moving from building i to building i+1 (0-indexed), If the current building's height is greater tha...
Python | Min Heap | With Explanation | Easy to Understand
1,800
furthest-building-you-can-reach
0.483
Mikey98
Medium
23,854
1,642
kth smallest instructions
class Solution: def kthSmallestPath(self, destination: List[int], k: int) -> str: m, n = destination # m "V" &amp; n "H" in total ans = "" while n: kk = comb(m+n-1, n-1) # (m+n-1 choose n-1) instructions starting with "H" if kk >= k: ans += "H" ...
https://leetcode.com/problems/kth-smallest-instructions/discuss/918429/Python3-greedy
5
Bob is standing at cell (0, 0), and he wants to reach destination: (row, column). He can only travel right and down. You are going to help Bob by providing instructions for him to reach destination. The instructions are represented as a string, where each character is either: 'H', meaning move horizontally (go right), ...
[Python3] greedy
286
kth-smallest-instructions
0.469
ye15
Hard
23,870
1,643
get maximum in generated array
class Solution: def getMaximumGenerated(self, n: int) -> int: max_nums = [0, 1, 1, 2, 2, 3, 3, 3, 3, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 9, 9, 11, 11, 11, 11, 11, 11, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13,...
https://leetcode.com/problems/get-maximum-in-generated-array/discuss/1754391/Python-O(1)-solution
18
You are given an integer n. A 0-indexed integer array nums of length n + 1 is generated in the following way: nums[0] = 0 nums[1] = 1 nums[2 * i] = nums[i] when 2 <= 2 * i <= n nums[2 * i + 1] = nums[i] + nums[i + 1] when 2 <= 2 * i + 1 <= n Return the maximum integer in the array nums. Example 1: Input: n = 7 Output...
Python O(1) solution
510
get-maximum-in-generated-array
0.502
wssx349
Easy
23,874
1,646
minimum deletions to make character frequencies unique
class Solution: def minDeletions(self, s: str) -> int: freq = {} # frequency table for c in s: freq[c] = 1 + freq.get(c, 0) ans = 0 seen = set() for k in sorted(freq.values(), reverse=True): while k in seen: k -= 1 ans ...
https://leetcode.com/problems/minimum-deletions-to-make-character-frequencies-unique/discuss/927527/Python3-most-to-least-frequent-characters
34
A string s is called good if there are no two different characters in s that have the same frequency. Given a string s, return the minimum number of characters you need to delete to make s good. The frequency of a character in a string is the number of times it appears in the string. For example, in the string "aab", t...
[Python3] most to least frequent characters
4,100
minimum-deletions-to-make-character-frequencies-unique
0.592
ye15
Medium
23,897
1,647
sell diminishing valued colored balls
class Solution: def maxProfit(self, inventory: List[int], orders: int) -> int: inventory.sort(reverse=True) # inventory high to low inventory += [0] ans = 0 k = 1 for i in range(len(inventory)-1): if inventory[i] > inventory[i+1]: if k*(inventor...
https://leetcode.com/problems/sell-diminishing-valued-colored-balls/discuss/927674/Python3-Greedy
32
You have an inventory of different colored balls, and there is a customer that wants orders balls of any color. The customer weirdly values the colored balls. Each colored ball's value is the number of balls of that color you currently have in your inventory. For example, if you own 6 yellow balls, the customer would p...
[Python3] Greedy
5,200
sell-diminishing-valued-colored-balls
0.305
ye15
Medium
23,927
1,648
defuse the bomb
class Solution: def decrypt(self, code: List[int], k: int) -> List[int]: if k == 0: return [0] * len(code) data = code + code result = [sum(data[i + 1: i + 1 + abs(k)]) for i in range(len(code))] # result = [] # for i in range(len(code)): # result.append(sum...
https://leetcode.com/problems/defuse-the-bomb/discuss/1903674/Python-Solution
2
You have a bomb to defuse, and your time is running out! Your informer will provide you with a circular array code of length of n and a key k. To decrypt the code, you must replace every number. All the numbers are replaced simultaneously. If k > 0, replace the ith number with the sum of the next k numbers. If k < 0, r...
Python Solution
142
defuse-the-bomb
0.612
hgalytoby
Easy
23,933
1,652
minimum deletions to make string balanced
class Solution: def minimumDeletions(self, s: str) -> int: # track the minimum number of deletions to make the current string balanced ending with 'a', 'b' end_a, end_b = 0,0 for val in s: if val == 'a': # to end with 'a', nothing to do with previous ending with ...
https://leetcode.com/problems/minimum-deletions-to-make-string-balanced/discuss/1020107/Python-DP-solution-easy-to-understand
12
You are given a string s consisting only of characters 'a' and 'b'. You can delete any number of characters in s to make s balanced. s is balanced if there is no pair of indices (i,j) such that i < j and s[i] = 'b' and s[j]= 'a'. Return the minimum number of deletions needed to make s balanced. Example 1: Input: s = ...
[Python] DP solution easy to understand
1,100
minimum-deletions-to-make-string-balanced
0.588
cloverpku
Medium
23,952
1,653
minimum jumps to reach home
class Solution: def minimumJumps(self, forbidden: List[int], a: int, b: int, x: int) -> int: forbidden = set(forbidden) limit = max(x,max(forbidden))+a+b seen = set() q = [(0,0,False)] while q: p,s,isb = q.pop(0) if p>limit or p<0 or p in forbidden or (p,isb) in seen: ...
https://leetcode.com/problems/minimum-jumps-to-reach-home/discuss/1540090/Simple-BFS-oror-Clean-and-Concise-oror-Well-coded
4
A certain bug's home is on the x-axis at position x. Help them get there from position 0. The bug jumps according to the following rules: It can jump exactly a positions forward (to the right). It can jump exactly b positions backward (to the left). It cannot jump backward twice in a row. It cannot jump to any forbidde...
📌📌 Simple BFS || Clean & Concise || Well-coded 🐍
618
minimum-jumps-to-reach-home
0.287
abhi9Rai
Medium
23,965
1,654
distribute repeating integers
class Solution: def canDistribute(self, nums: List[int], quantity: List[int]) -> bool: freq = {} for x in nums: freq[x] = 1 + freq.get(x, 0) vals = sorted(freq.values(), reverse=True) quantity.sort(reverse=True) # pruning - large values first def fn(i): ...
https://leetcode.com/problems/distribute-repeating-integers/discuss/1103429/Python3-backtracking
2
You are given an array of n integers, nums, where there are at most 50 unique values in the array. You are also given an array of m customer order quantities, quantity, where quantity[i] is the amount of integers the ith customer ordered. Determine if it is possible to distribute nums such that: The ith customer gets e...
[Python3] backtracking
159
distribute-repeating-integers
0.392
ye15
Hard
23,971
1,655
determine if two strings are close
class Solution: def closeStrings(self, word1: str, word2: str) -> bool: cnt1, cnt2 = Counter(word1), Counter(word2) return cnt1.keys() == cnt2.keys() and sorted(cnt1.values()) == sorted(cnt2.values())
https://leetcode.com/problems/determine-if-two-strings-are-close/discuss/935962/Python3-2-line-via-counter
2
Two strings are considered close if you can attain one from the other using the following operations: Operation 1: Swap any two existing characters. For example, abcde -> aecdb Operation 2: Transform every occurrence of one existing character into another existing character, and do the same with the other character. Fo...
[Python3] 2-line via counter
112
determine-if-two-strings-are-close
0.541
ye15
Medium
23,973
1,657
minimum operations to reduce x to zero
class Solution: def minOperations(self, nums: List[int], x: int) -> int: mp = {0: 0} prefix = 0 for i, num in enumerate(nums, 1): prefix += num mp[prefix] = i ans = mp.get(x, inf) for i, num in enumerate(reversed(nums), 1): ...
https://leetcode.com/problems/minimum-operations-to-reduce-x-to-zero/discuss/935986/Python3-O(N)-hash-table-of-prefix
21
You are given an integer array nums and an integer x. In one operation, you can either remove the leftmost or the rightmost element from the array nums and subtract its value from x. Note that this modifies the array for future operations. Return the minimum number of operations to reduce x to exactly 0 if it is possib...
[Python3] O(N) hash table of prefix
1,600
minimum-operations-to-reduce-x-to-zero
0.376
ye15
Medium
23,983
1,658
maximize grid happiness
class Solution: def getMaxGridHappiness(self, m: int, n: int, introvertsCount: int, extrovertsCount: int) -> int: @cache def fn(prev, i, j, intro, extro): """Return max grid happiness at (i, j).""" if i == m: return 0 # no more position if j == n: return...
https://leetcode.com/problems/maximize-grid-happiness/discuss/1132982/Python3-top-down-dp
1
You are given four integers, m, n, introvertsCount, and extrovertsCount. You have an m x n grid, and there are two types of people: introverts and extroverts. There are introvertsCount introverts and extrovertsCount extroverts. You should decide how many people you want to live in the grid and assign each of them one g...
[Python3] top-down dp
319
maximize-grid-happiness
0.384
ye15
Hard
23,992
1,659
check if two string arrays are equivalent
class Solution: def arrayStringsAreEqual(self, word1: List[str], word2: List[str]) -> bool: return ''.join(word1) == ''.join(word2)
https://leetcode.com/problems/check-if-two-string-arrays-are-equivalent/discuss/944697/Python-3-or-Python-1-liner-or-No-explanation
15
Given two string arrays word1 and word2, return true if the two arrays represent the same string, and false otherwise. A string is represented by an array if the array elements concatenated in order forms the string. Example 1: Input: word1 = ["ab", "c"], word2 = ["a", "bc"] Output: true Explanation: word1 represents...
Python 3 | Python 1-liner | No explanation 😄
1,200
check-if-two-string-arrays-are-equivalent
0.833
idontknoooo
Easy
23,993
1,662
smallest string with a given numeric value
class Solution: def getSmallestString(self, n: int, k: int) -> str: res, k, i = ['a'] * n, k - n, n - 1 while k: k += 1 if k/26 >= 1: res[i], k, i = 'z', k - 26, i - 1 else: res[i], k = chr(k + 96), 0 return ''.join(res)
https://leetcode.com/problems/smallest-string-with-a-given-numeric-value/discuss/1871793/Python3-GREEDY-FILLING-()-Explained
56
The numeric value of a lowercase character is defined as its position (1-indexed) in the alphabet, so the numeric value of a is 1, the numeric value of b is 2, the numeric value of c is 3, and so on. The numeric value of a string consisting of lowercase characters is defined as the sum of its characters' numeric values...
✔️ [Python3] GREEDY FILLING (🌸¬‿¬), Explained
2,900
smallest-string-with-a-given-numeric-value
0.668
artod
Medium
24,045
1,663
ways to make a fair array
class Solution: def waysToMakeFair(self, nums: List[int]) -> int: if len(nums) == 1: return 1 if len(nums) == 2: return 0 prefixEven = sum(nums[2::2]) prefixOdd = sum(nums[1::2]) result = 0 if prefixEven == prefixOdd and len(set(nums)) == 1: result += 1 for i in range(1,len(nums)): if i =...
https://leetcode.com/problems/ways-to-make-a-fair-array/discuss/1775588/WEEB-EXPLAINS-PYTHONC%2B%2B-DPPREFIX-SUM-SOLN
6
You are given an integer array nums. You can choose exactly one index (0-indexed) and remove the element. Notice that the index of the elements may change after the removal. For example, if nums = [6,1,7,4,1]: Choosing to remove index 1 results in nums = [6,7,4,1]. Choosing to remove index 2 results in nums = [6,1,4,1]...
WEEB EXPLAINS PYTHON/C++ DP/PREFIX SUM SOLN
264
ways-to-make-a-fair-array
0.635
Skywalker5423
Medium
24,088
1,664
minimum initial energy to finish tasks
class Solution: def minimumEffort(self, tasks: List[List[int]]) -> int: tasks.sort(key=lambda x: x[0]-x[1]) def ok(mid): for actual, minimum in tasks: if minimum > mid or actual > mid: return False if minimum <= mid: mid -= actual return True ...
https://leetcode.com/problems/minimum-initial-energy-to-finish-tasks/discuss/944714/Python-3-or-Sort-%2B-Greedy-and-Sort-%2B-Binary-Search-or-Explanation
2
You are given an array tasks where tasks[i] = [actuali, minimumi]: actuali is the actual amount of energy you spend to finish the ith task. minimumi is the minimum amount of energy you require to begin the ith task. For example, if the task is [10, 12] and your current energy is 11, you cannot start this task. However,...
Python 3 | Sort + Greedy & Sort + Binary Search | Explanation
173
minimum-initial-energy-to-finish-tasks
0.562
idontknoooo
Hard
24,100
1,665
maximum repeating substring
class Solution: def maxRepeating(self, sequence: str, word: str) -> int: i = 0 while word*(i+1) in sequence: i+=1 return i
https://leetcode.com/problems/maximum-repeating-substring/discuss/1400359/Python3-Simple-Solution
4
For a string sequence, a string word is k-repeating if word concatenated k times is a substring of sequence. The word's maximum k-repeating value is the highest value k where word is k-repeating in sequence. If word is not a substring of sequence, word's maximum k-repeating value is 0. Given strings sequence and word, ...
Python3, Simple Solution
306
maximum-repeating-substring
0.396
Flerup
Easy
24,110
1,668
merge in between linked lists
class Solution: def mergeInBetween(self, list1: ListNode, a: int, b: int, list2: ListNode) -> ListNode: curr=list1 for count in range(b): if count==a-1: # travel to a node and --> step 1 start=curr # then save pointer in start curr=curr.next # co...
https://leetcode.com/problems/merge-in-between-linked-lists/discuss/1833998/Python3-oror-Explanation-and-Example
2
You are given two linked lists: list1 and list2 of sizes n and m respectively. Remove list1's nodes from the ath node to the bth node, and put list2 in their place. The blue edges and nodes in the following figure indicate the result: Build the result list and return its head. Example 1: Input: list1 = [10,1,13,6,9,5...
Python3 || Explanation & Example
48
merge-in-between-linked-lists
0.745
rushi_javiya
Medium
24,129
1,669
minimum number of removals to make mountain array
class Solution: def minimumMountainRemovals(self, lst: List[int]) -> int: l = len(lst) dp = [0] * l dp1 = [0] * l for i in range(l): # for increasing subsequence maxi = 0 for j in range(i): if lst[i] > lst[j]: if dp[j] > maxi: maxi = dp[j] dp[i] = maxi + 1 for i in range(l - 1, -...
https://leetcode.com/problems/minimum-number-of-removals-to-make-mountain-array/discuss/1543614/Python-oror-Easy-Solution
2
You may recall that an array arr is a mountain array if and only if: arr.length >= 3 There exists some index i (0-indexed) with 0 < i < arr.length - 1 such that: arr[0] < arr[1] < ... < arr[i - 1] < arr[i] arr[i] > arr[i + 1] > ... > arr[arr.length - 1] Given an integer array nums, return the minimum number of elements...
Python || Easy Solution
209
minimum-number-of-removals-to-make-mountain-array
0.425
naveenrathore
Hard
24,141
1,671
richest customer wealth
class Solution: def maximumWealth(self, accounts: List[List[int]]) -> int: return max([sum(acc) for acc in accounts])
https://leetcode.com/problems/richest-customer-wealth/discuss/2675823/Python-or-1-liner-simple-solution
36
You are given an m x n integer grid accounts where accounts[i][j] is the amount of money the ith customer has in the jth bank. Return the wealth that the richest customer has. A customer's wealth is the amount of money they have in all their bank accounts. The richest customer is the customer that has the maximum wealt...
Python | 1-liner simple solution
2,200
richest-customer-wealth
0.882
LordVader1
Easy
24,144
1,672
find the most competitive subsequence
class Solution: def mostCompetitive(self, nums: List[int], k: int) -> List[int]: stack = [] # (increasing) mono-stack for i, x in enumerate(nums): while stack and stack[-1] > x and len(stack) + len(nums) - i > k: stack.pop() if len(stack) < k: stack.append(x) return...
https://leetcode.com/problems/find-the-most-competitive-subsequence/discuss/953711/Python3-greedy-O(N)
6
Given an integer array nums and a positive integer k, return the most competitive subsequence of nums of size k. An array's subsequence is a resulting sequence obtained by erasing some (possibly zero) elements from the array. We define that a subsequence a is more competitive than a subsequence b (of the same length) i...
[Python3] greedy O(N)
342
find-the-most-competitive-subsequence
0.493
ye15
Medium
24,193
1,673
minimum moves to make array complementary
class Solution: def minMoves(self, nums: List[int], limit: int) -> int: n = len(nums) overlay_arr = [0] * (2*limit+2) for i in range(n//2): left_boundary = min(nums[i], nums[n-1-i]) + 1 no_move_value = nums[i] + nums[n-1-i] right_boundary = max(nums[i], ...
https://leetcode.com/problems/minimum-moves-to-make-array-complementary/discuss/1650877/Sweep-Algorithm-or-Explained-Python
5
You are given an integer array nums of even length n and an integer limit. In one move, you can replace any integer from nums with another integer between 1 and limit, inclusive. The array nums is complementary if for all indices i (0-indexed), nums[i] + nums[n - 1 - i] equals the same number. For example, the array [1...
Sweep Algorithm | Explained [Python]
397
minimum-moves-to-make-array-complementary
0.386
xyz76
Medium
24,201
1,674
minimize deviation in array
class Solution: def minimumDeviation(self, nums: List[int]) -> int: from sortedcontainers import SortedList for i in range(len(nums)): if nums[i]%2!=0: nums[i]=nums[i]*2 nums = SortedList(nums) result = 100000000000 while True: min_value = nums[0] max_value = nums[-1] if max_value % 2 ...
https://leetcode.com/problems/minimize-deviation-in-array/discuss/1782626/Python-Simple-Python-Solution-By-SortedList
10
You are given an array nums of n positive integers. You can perform two types of operations on any element of the array any number of times: If the element is even, divide it by 2. For example, if the array is [1,2,3,4], then you can do this operation on the last element, and the array will be [1,2,3,2]. If the element...
[ Python ] ✔✔ Simple Python Solution By SortedList 🔥✌
563
minimize-deviation-in-array
0.52
ASHOK_KUMAR_MEGHVANSHI
Hard
24,204
1,675
goal parser interpretation
class Solution: def interpret(self, command: str) -> str: return command.replace('()','o').replace('(al)','al')
https://leetcode.com/problems/goal-parser-interpretation/discuss/961441/Python-one-liner
92
You own a Goal Parser that can interpret a string command. The command consists of an alphabet of "G", "()" and/or "(al)" in some order. The Goal Parser will interpret "G" as the string "G", "()" as the string "o", and "(al)" as the string "al". The interpreted strings are then concatenated in the original order. Given...
Python one-liner
8,000
goal-parser-interpretation
0.861
lokeshsenthilkumar
Easy
24,208
1,678
max number of k sum pairs
class Solution: def maxOperations(self, nums: List[int], k: int) -> int: counter = defaultdict(int) count = 0 for x in nums: comp = k - x if counter[comp]>0: counter[comp]-=1 count+=1 else: counter[x...
https://leetcode.com/problems/max-number-of-k-sum-pairs/discuss/2005867/Python-Simple-One-Pass
2
You are given an integer array nums and an integer k. In one operation, you can pick two numbers from the array whose sum equals k and remove them from the array. Return the maximum number of operations you can perform on the array. Example 1: Input: nums = [1,2,3,4], k = 5 Output: 2 Explanation: Starting with nums =...
Python Simple One Pass
181
max-number-of-k-sum-pairs
0.573
constantine786
Medium
24,253
1,679
concatenation of consecutive binary numbers
class Solution: def concatenatedBinary(self, n: int) -> int: return int("".join([bin(i)[2:] for i in range(1,n+1)]),2)%(10**9+7)
https://leetcode.com/problems/concatenation-of-consecutive-binary-numbers/discuss/2612717/python-one-line-solution-94-beats
5
Given an integer n, return the decimal value of the binary string formed by concatenating the binary representations of 1 to n in order, modulo 109 + 7. Example 1: Input: n = 1 Output: 1 Explanation: "1" in binary corresponds to the decimal value 1. Example 2: Input: n = 3 Output: 27 Explanation: In binary, 1, 2, an...
python one line solution 94% beats
677
concatenation-of-consecutive-binary-numbers
0.57
benon
Medium
24,298
1,680
minimum incompatibility
class Solution: def minimumIncompatibility(self, nums: List[int], k: int) -> int: nums.sort() def fn(i, cand): """Populate stack and compute minimum incompatibility.""" nonlocal ans if cand + len(nums) - i - sum(not x for x in stack) > ans: return ...
https://leetcode.com/problems/minimum-incompatibility/discuss/965262/Python3-backtracking
3
You are given an integer array nums and an integer k. You are asked to distribute this array into k subsets of equal size such that there are no two equal elements in the same subset. A subset's incompatibility is the difference between the maximum and minimum elements in that array. Return the minimum possible sum of ...
[Python3] backtracking
156
minimum-incompatibility
0.374
ye15
Hard
24,343
1,681
count the number of consistent strings
class Solution: def countConsistentStrings(self, allowed: str, words: List[str]) -> int: return sum(set(allowed) >= set(i) for i in words)
https://leetcode.com/problems/count-the-number-of-consistent-strings/discuss/1054303/Python-simple-one-liner
12
You are given a string allowed consisting of distinct characters and an array of strings words. A string is consistent if all characters in the string appear in the string allowed. Return the number of consistent strings in the array words. Example 1: Input: allowed = "ab", words = ["ad","bd","aaab","baa","badab"] Ou...
Python - simple one liner
828
count-the-number-of-consistent-strings
0.819
angelique_
Easy
24,347
1,684
sum of absolute differences in a sorted array
class Solution: def getSumAbsoluteDifferences(self, nums: List[int]) -> List[int]: pre_sum = [0] for num in nums: # calculate prefix sum pre_sum.append(pre_sum[-1] + num) n = len(nums) # render the output ...
https://leetcode.com/problems/sum-of-absolute-differences-in-a-sorted-array/discuss/1439047/Python-3-or-O(N)-Prefix-Sum-Clean-or-Explanation
3
You are given an integer array nums sorted in non-decreasing order. Build and return an integer array result with the same length as nums such that result[i] is equal to the summation of absolute differences between nums[i] and all the other elements in the array. In other words, result[i] is equal to sum(|nums[i]-nums...
Python 3 | O(N), Prefix Sum, Clean | Explanation
327
sum-of-absolute-differences-in-a-sorted-array
0.649
idontknoooo
Medium
24,396
1,685
stone game vi
class Solution: def stoneGameVI(self, alice: List[int], bob: List[int]) -> int: n = len(alice) arr = [alice[i] + bob[i] for i in range(n)] s = sum(bob) res = 0 k = (n+1)//2 arr.sort(reverse=True) for i in range(0, n, 2): res += arr[i] ...
https://leetcode.com/problems/stone-game-vi/discuss/1860830/python-easy-solution-using-sort
0
Alice and Bob take turns playing a game, with Alice starting first. There are n stones in a pile. On each player's turn, they can remove a stone from the pile and receive points based on the stone's value. Alice and Bob may value the stones differently. You are given two integer arrays of length n, aliceValues and bobV...
python easy solution using sort
85
stone-game-vi
0.544
byuns9334
Medium
24,408
1,686
delivering boxes from storage to ports
class Solution: def boxDelivering(self, boxes: List[List[int]], portsCount: int, maxBoxes: int, maxWeight: int) -> int: dp = [0] + [inf]*len(boxes) trips = 2 ii = 0 for i in range(len(boxes)): maxWeight -= boxes[i][1] if i and boxes[i-1][0] != boxes[i][0]: tri...
https://leetcode.com/problems/delivering-boxes-from-storage-to-ports/discuss/1465884/Python3-dp-%2B-greedy
1
You have the task of delivering some boxes from storage to their ports using only one ship. However, this ship has a limit on the number of boxes and the total weight that it can carry. You are given an array boxes, where boxes[i] = [portsi, weighti], and three integers portsCount, maxBoxes, and maxWeight. portsi is th...
[Python3] dp + greedy
204
delivering-boxes-from-storage-to-ports
0.385
ye15
Hard
24,410
1,687
count of matches in tournament
class Solution: def numberOfMatches(self, n: int) -> int: # the logic is, among n teams only 1 team will won, so n-1 teams will lose # hence there will be n-1 match (so that n-1 teams can lose) return n-1
https://leetcode.com/problems/count-of-matches-in-tournament/discuss/1276389/simple-python-solution-easy-to-understand
4
You are given an integer n, the number of teams in a tournament that has strange rules: If the current number of teams is even, each team gets paired with another team. A total of n / 2 matches are played, and n / 2 teams advance to the next round. If the current number of teams is odd, one team randomly advances in th...
simple python solution-easy to understand
272
count-of-matches-in-tournament
0.832
nandanabhishek
Easy
24,411
1,688
partitioning into minimum number of deci binary numbers
class Solution: def minPartitions(self, n: str) -> int: return int(max(n))
https://leetcode.com/problems/partitioning-into-minimum-number-of-deci-binary-numbers/discuss/2202648/C%2B%2BJavaPython-Easy-One-liner-with-explanation
52
A decimal number is called deci-binary if each of its digits is either 0 or 1 without any leading zeros. For example, 101 and 1100 are deci-binary, while 112 and 3001 are not. Given a string n that represents a positive decimal integer, return the minimum number of positive deci-binary numbers needed so that they sum u...
[C++/Java/Python]- Easy One liner with explanation
3,800
partitioning-into-minimum-number-of-deci-binary-numbers
0.896
constantine786
Medium
24,443
1,689
stone game vii
class Solution: def stoneGameVII(self, stones: List[int]) -> int: dp = [[0 for _ in range(len(stones))] for _ in range(len(stones))] # dp table n x n run_sum = [0] # running sum -> sum [i..j] = run_sum[j] - run_sum[i] s = 0 ## Calculation of running ...
https://leetcode.com/problems/stone-game-vii/discuss/971804/Python3-Easy-code-with-explanation-DP
9
Alice and Bob take turns playing a game, with Alice starting first. There are n stones arranged in a row. On each player's turn, they can remove either the leftmost stone or the rightmost stone from the row and receive points equal to the sum of the remaining stones' values in the row. The winner is the one with the hi...
[Python3] Easy code with explanation - DP
851
stone-game-vii
0.586
mihirrane
Medium
24,486
1,690
maximum height by stacking cuboids
class Solution: def maxHeight(self, cuboids: List[List[int]]) -> int: cuboids = sorted([sorted(cub) for cub in cuboids], reverse=True) # sort LxWxH in cube, then sort cube reversely ok = lambda x, y: (x[0] >= y[0] and x[1] >= y[1] and x[2] >= y[2]) # make a lambda function to verify whether y can ...
https://leetcode.com/problems/maximum-height-by-stacking-cuboids/discuss/970397/Python-3-or-DP-Sort-O(N2)-or-Explanation
7
Given n cuboids where the dimensions of the ith cuboid is cuboids[i] = [widthi, lengthi, heighti] (0-indexed). Choose a subset of cuboids and place them on each other. You can place cuboid i on cuboid j if widthi <= widthj and lengthi <= lengthj and heighti <= heightj. You can rearrange any cuboid's dimensions by rotat...
Python 3 | DP, Sort, O(N^2) | Explanation
425
maximum-height-by-stacking-cuboids
0.541
idontknoooo
Hard
24,492
1,691
reformat phone number
class Solution: def reformatNumber(self, number: str) -> str: number = number.replace("-", "").replace(" ", "") # removing - and space ans = [] for i in range(0, len(number), 3): if len(number) - i != 4: ans.append(number[i:i+3]) else: ans.extend([n...
https://leetcode.com/problems/reformat-phone-number/discuss/978512/Python3-string-processing
13
You are given a phone number as a string number. number consists of digits, spaces ' ', and/or dashes '-'. You would like to reformat the phone number in a certain manner. Firstly, remove all spaces and dashes. Then, group the digits from left to right into blocks of length 3 until there are 4 or fewer digits. The fina...
[Python3] string processing
676
reformat-phone-number
0.649
ye15
Easy
24,498
1,694
maximum erasure value
class Solution: def maximumUniqueSubarray(self, nums: List[int]) -> int: counter=defaultdict(int) # track count of elements in the window res=i=tot=0 for j in range(len(nums)): x=nums[j] tot+=x counter[x]+=1 # adjust the left bound of sl...
https://leetcode.com/problems/maximum-erasure-value/discuss/2140512/Python-Easy-2-approaches
15
You are given an array of positive integers nums and want to erase a subarray containing unique elements. The score you get by erasing the subarray is equal to the sum of its elements. Return the maximum score you can get by erasing exactly one subarray. An array b is called to be a subarray of a if it forms a contiguo...
✅ Python Easy 2 approaches
1,400
maximum-erasure-value
0.577
constantine786
Medium
24,519
1,695
jump game vi
class Solution: def maxResult(self, nums: List[int], k: int) -> int: pq = [] # max heap for i in reversed(range(len(nums))): while pq and pq[0][1] - i > k: heappop(pq) ans = nums[i] - pq[0][0] if pq else nums[i] heappush(pq, (-ans, i)) return ans
https://leetcode.com/problems/jump-game-vi/discuss/978563/Python3-range-max
7
You are given a 0-indexed integer array nums and an integer k. You are initially standing at index 0. In one move, you can jump at most k steps forward without going outside the boundaries of the array. That is, you can jump from index i to any index in the range [i + 1, min(n - 1, i + k)] inclusive. You want to reach ...
[Python3] range max
504
jump-game-vi
0.463
ye15
Medium
24,557
1,696
checking existence of edge length limited paths
class Solution: def distanceLimitedPathsExist(self, n: int, edgeList: List[List[int]], queries: List[List[int]]) -> List[bool]: parent = [i for i in range(n+1)] rank = [0 for i in range(n+1)] def find(parent, x): if parent[x] == x: return x ...
https://leetcode.com/problems/checking-existence-of-edge-length-limited-paths/discuss/981352/Python3-Union-find
0
An undirected graph of n nodes is defined by edgeList, where edgeList[i] = [ui, vi, disi] denotes an edge between nodes ui and vi with distance disi. Note that there may be multiple edges between two nodes. Given an array queries, where queries[j] = [pj, qj, limitj], your task is to determine for each queries[j] whethe...
Python3 Union find
80
checking-existence-of-edge-length-limited-paths
0.502
ermolushka2
Hard
24,570
1,697
number of students unable to eat lunch
class Solution: def countStudents(self, students: List[int], sandwiches: List[int]) -> int: curr = 0 while students: if(students[0] == sandwiches[0]): curr = 0 students.pop(0) sandwiches.pop(0) else: cur...
https://leetcode.com/problems/number-of-students-unable-to-eat-lunch/discuss/1228863/Python3-32ms-Brute-Force-Solution
11
The school cafeteria offers circular and square sandwiches at lunch break, referred to by numbers 0 and 1 respectively. All students stand in a queue. Each student either prefers square or circular sandwiches. The number of sandwiches in the cafeteria is equal to the number of students. The sandwiches are placed in a s...
[Python3] 32ms Brute Force Solution
442
number-of-students-unable-to-eat-lunch
0.679
VoidCupboard
Easy
24,572
1,700
average waiting time
class Solution: def averageWaitingTime(self, customers: List[List[int]]) -> float: arr = [] time = 0 for i , j in customers: if(i > time): time = i + j else: time += j arr.append(time - i) ...
https://leetcode.com/problems/average-waiting-time/discuss/1236349/Python3-Simple-And-Fast-Solution
6
There is a restaurant with a single chef. You are given an array customers, where customers[i] = [arrivali, timei]: arrivali is the arrival time of the ith customer. The arrival times are sorted in non-decreasing order. timei is the time needed to prepare the order of the ith customer. When a customer arrives, he gives...
[Python3] Simple And Fast Solution
194
average-waiting-time
0.624
VoidCupboard
Medium
24,612
1,701
maximum binary string after change
lass Solution: def maximumBinaryString(self, s: str) -> str: #count of 0 c=0 #final ans string will contain only one zero.therefore shift the first 0 to c places.Initialize ans string with all 1s lst=["1"]*len(s) for i in range (0,len(s)): if s[i]=="0": ...
https://leetcode.com/problems/maximum-binary-string-after-change/discuss/1382851/python-3-oror-clean-oror-easy-approach
4
You are given a binary string binary consisting of only 0's or 1's. You can apply each of the following operations any number of times: Operation 1: If the number contains the substring "00", you can replace it with "10". For example, "00010" -> "10010" Operation 2: If the number contains the substring "10", you can re...
python 3 || clean || easy approach
175
maximum-binary-string-after-change
0.462
minato_namikaze
Medium
24,622
1,702
minimum adjacent swaps for k consecutive ones
class Solution: def minMoves(self, nums: List[int], k: int) -> int: ii = val = 0 ans = inf loc = [] # location of 1s for i, x in enumerate(nums): if x: loc.append(i) m = (ii + len(loc) - 1)//2 # median val += loc[-1] - l...
https://leetcode.com/problems/minimum-adjacent-swaps-for-k-consecutive-ones/discuss/1002574/Python3-1-pass-O(N)
2
You are given an integer array, nums, and an integer k. nums comprises of only 0's and 1's. In one move, you can choose two adjacent indices and swap their values. Return the minimum number of moves required so that nums has k consecutive 1's. Example 1: Input: nums = [1,0,0,1,0,1], k = 2 Output: 1 Explanation: In 1 ...
[Python3] 1-pass O(N)
572
minimum-adjacent-swaps-for-k-consecutive-ones
0.423
ye15
Hard
24,630
1,703
determine if string halves are alike
class Solution: def halvesAreAlike(self, s: str) -> bool: vowels = set('aeiouAEIOU') count = 0 for i in range(len(s)//2): if s[i] in vowels: count+=1 if s[-i-1] in vowels: count-=1 return count == 0
https://leetcode.com/problems/determine-if-string-halves-are-alike/discuss/991430/Runtime-is-faster-than-98-and-the-memory-usage-is-less-than-90-Python-3-Accepted
5
You are given a string s of even length. Split this string into two halves of equal lengths, and let a be the first half and b be the second half. Two strings are alike if they have the same number of vowels ('a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'). Notice that s contains uppercase and lowercase letters. Retu...
Runtime is faster than 98% and the memory usage is less than 90% Python 3 [Accepted]
341
determine-if-string-halves-are-alike
0.774
WiseLin
Easy
24,632
1,704
maximum number of eaten apples
class Solution: def eatenApples(self, apples: List[int], days: List[int]) -> int: ans = 0 pq = [] # min-heap for i, (x, d) in enumerate(zip(apples, days)): while pq and pq[0][0] <= i: heappop(pq) # rotten if x: heappush(pq, (i+d, x)) if pq: ...
https://leetcode.com/problems/maximum-number-of-eaten-apples/discuss/988437/Python3-priority-queue
3
There is a special kind of apple tree that grows apples every day for n days. On the ith day, the tree grows apples[i] apples that will rot after days[i] days, that is on day i + days[i] the apples will be rotten and cannot be eaten. On some days, the apple tree does not grow any apples, which are denoted by apples[i] ...
[Python3] priority queue
113
maximum-number-of-eaten-apples
0.381
ye15
Medium
24,687
1,705
where will the ball fall
class Solution: def findBall(self, grid: List[List[int]]) -> List[int]: m, n = len(grid), len(grid[0]) @cache def helper(r, c): if r == m: return c elif grid[r][c] == 1 and c+1 < n and grid[r][c+1] == 1: return helper(r+1, c+1) ...
https://leetcode.com/problems/where-will-the-ball-fall/discuss/1443268/Python-3-or-DFS-Simulation-or-Explanation
28
You have a 2-D grid of size m x n representing a box, and you have n balls. The box is open on the top and bottom sides. Each cell in the box has a diagonal board spanning two corners of the cell that can redirect a ball to the right or to the left. A board that redirects the ball to the right spans the top-left corner...
Python 3 | DFS, Simulation | Explanation
1,400
where-will-the-ball-fall
0.716
idontknoooo
Medium
24,689
1,706
maximum xor with an element from array
class Solution: def maximizeXor(self, nums: List[int], queries: List[List[int]]) -> List[int]: nums.sort() queries = sorted((m, x, i) for i, (x, m) in enumerate(queries)) ans = [-1]*len(queries) trie = {} k = 0 for m, x, i in queries: while k < l...
https://leetcode.com/problems/maximum-xor-with-an-element-from-array/discuss/988468/Python3-trie
17
You are given an array nums consisting of non-negative integers. You are also given a queries array, where queries[i] = [xi, mi]. The answer to the ith query is the maximum bitwise XOR value of xi and any element of nums that does not exceed mi. In other words, the answer is max(nums[j] XOR xi) for all j such that nums...
[Python3] trie
773
maximum-xor-with-an-element-from-array
0.442
ye15
Hard
24,743
1,707
maximum units on a truck
class Solution: def maximumUnits(self, boxTypes: List[List[int]], truckSize: int) -> int: boxTypes.sort(key=lambda x:x[1],reverse=1) s=0 for i,j in boxTypes: i=min(i,truckSize) s+=i*j truckSize-=i if truckSize==0: break ...
https://leetcode.com/problems/maximum-units-on-a-truck/discuss/999230/Python-Simple-solution
30
You are assigned to put some amount of boxes onto one truck. You are given a 2D array boxTypes, where boxTypes[i] = [numberOfBoxesi, numberOfUnitsPerBoxi]: numberOfBoxesi is the number of boxes of type i. numberOfUnitsPerBoxi is the number of units in each box of the type i. You are also given an integer truckSize, whi...
[Python] Simple solution
4,500
maximum-units-on-a-truck
0.739
lokeshsenthilkumar
Easy
24,744
1,710
count good meals
class Solution: def countPairs(self, deliciousness: List[int]) -> int: ans = 0 freq = defaultdict(int) for x in deliciousness: for k in range(22): ans += freq[2**k - x] freq[x] += 1 return ans % 1_000_000_007
https://leetcode.com/problems/count-good-meals/discuss/999170/Python3-frequency-table
43
A good meal is a meal that contains exactly two different food items with a sum of deliciousness equal to a power of two. You can pick any two different foods to make a good meal. Given an array of integers deliciousness where deliciousness[i] is the deliciousness of the ith item of food, return the number of different...
[Python3] frequency table
4,100
count-good-meals
0.29
ye15
Medium
24,793
1,711
ways to split array into three subarrays
class Solution: def waysToSplit(self, nums: List[int]) -> int: prefix = [0] for x in nums: prefix.append(prefix[-1] + x) ans = 0 for i in range(1, len(nums)): j = bisect_left(prefix, 2*prefix[i]) k = bisect_right(prefix, (prefix[i] + prefix[-1])//2) ...
https://leetcode.com/problems/ways-to-split-array-into-three-subarrays/discuss/999157/Python3-binary-search-and-2-pointer
65
A split of an integer array is good if: The array is split into three non-empty contiguous subarrays - named left, mid, right respectively from left to right. The sum of the elements in left is less than or equal to the sum of the elements in mid, and the sum of the elements in mid is less than or equal to the sum of t...
[Python3] binary search & 2-pointer
4,900
ways-to-split-array-into-three-subarrays
0.325
ye15
Medium
24,801
1,712
minimum operations to make a subsequence
class Solution: def minOperations(self, target: List[int], arr: List[int]) -> int: loc = {x: i for i, x in enumerate(target)} stack = [] for x in arr: if x in loc: i = bisect_left(stack, loc[x]) if i < len(stack): stack[i] = loc[x] ...
https://leetcode.com/problems/minimum-operations-to-make-a-subsequence/discuss/999141/Python3-binary-search
5
You are given an array target that consists of distinct integers and another integer array arr that can have duplicates. In one operation, you can insert any integer at any position in arr. For example, if arr = [1,4,1,2], you can add 3 in the middle and make it [1,4,3,1,2]. Note that you can insert the integer at the ...
[Python3] binary search
294
minimum-operations-to-make-a-subsequence
0.492
ye15
Hard
24,810
1,713
calculate money in leetcode bank
class Solution: def totalMoney(self, n: int) -> int: res,k=0,0 for i in range(n): if i%7==0: k+=1 res+=k+(i%7) return res
https://leetcode.com/problems/calculate-money-in-leetcode-bank/discuss/1138960/Python-3-very-easy-solution
5
Hercy wants to save money for his first car. He puts money in the Leetcode bank every day. He starts by putting in $1 on Monday, the first day. Every day from Tuesday to Sunday, he will put in $1 more than the day before. On every subsequent Monday, he will put in $1 more than the previous Monday. Given n, return the t...
Python 3 very easy solution
367
calculate-money-in-leetcode-bank
0.652
lin11116459
Easy
24,813
1,716
maximum score from removing substrings
class Solution: def maximumGain(self, s: str, x: int, y: int) -> int: # to calculate first, high value of x or y a, b = 'ab', 'ba' if y > x: b, a, y, x = a, b, x, y answer = 0 for word in [a, b]: stack = [] i = 0 while i < ...
https://leetcode.com/problems/maximum-score-from-removing-substrings/discuss/1009152/Python-solution-with-explanation
9
You are given a string s and two integers x and y. You can perform two types of operations any number of times. Remove substring "ab" and gain x points. For example, when removing "ab" from "cabxbae" it becomes "cxbae". Remove substring "ba" and gain y points. For example, when removing "ba" from "cabxbae" it becomes "...
Python solution with explanation💃🏻
602
maximum-score-from-removing-substrings
0.461
just_4ina
Medium
24,848
1,717
construct the lexicographically largest valid sequence
class Solution: def constructDistancedSequence(self, n: int) -> List[int]: arr = [0]*(2*n-1) # the array we want to put numbers. 0 means no number has been put here i = 0 # current index to put a number vi = [False] * (n+1) # check if we have use...
https://leetcode.com/problems/construct-the-lexicographically-largest-valid-sequence/discuss/1008948/Python-Greedy%2BBacktracking-or-Well-Explained-or-Comments
23
Given an integer n, find a sequence that satisfies all of the following: The integer 1 occurs once in the sequence. Each integer between 2 and n occurs twice in the sequence. For every integer i between 2 and n, the distance between the two occurrences of i is exactly i. The distance between two numbers on the sequence...
Python Greedy+Backtracking | Well Explained | Comments
1,800
construct-the-lexicographically-largest-valid-sequence
0.516
etoss
Medium
24,850
1,718
number of ways to reconstruct a tree
class Solution: def checkWays(self, pairs: List[List[int]]) -> int: graph = {} for x, y in pairs: graph.setdefault(x, set()).add(y) graph.setdefault(y, set()).add(x) ans = 1 ancestors = set() for n in sorted(graph, key=lambda x: len(graph[x]...
https://leetcode.com/problems/number-of-ways-to-reconstruct-a-tree/discuss/1128518/Python3-greedy
5
You are given an array pairs, where pairs[i] = [xi, yi], and: There are no duplicates. xi < yi Let ways be the number of rooted trees that satisfy the following conditions: The tree consists of nodes whose values appeared in pairs. A pair [xi, yi] exists in pairs if and only if xi is an ancestor of yi or yi is an ances...
[Python3] greedy
330
number-of-ways-to-reconstruct-a-tree
0.43
ye15
Hard
24,855
1,719
decode xored array
class Solution: def decode(self, encoded: List[int], first: int) -> List[int]: return [first] + [first:= first ^ x for x in encoded]
https://leetcode.com/problems/decode-xored-array/discuss/1075067/Python-1-Liner-(List-Comprehension-with-Assignment-Expresion)
17
There is a hidden integer array arr that consists of n non-negative integers. It was encoded into another integer array encoded of length n - 1, such that encoded[i] = arr[i] XOR arr[i + 1]. For example, if arr = [1,0,2,1], then encoded = [1,2,3]. You are given the encoded array. You are also given an integer first, th...
Python - 1 Liner (List Comprehension with Assignment Expresion)
957
decode-xored-array
0.86
leeteatsleep
Easy
24,857
1,720
swapping nodes in a linked list
class Solution: def swapNodes(self, head: Optional[ListNode], k: int) -> Optional[ListNode]: l = head # left node for _ in range(k-1): l = l.next # the rest of the code logic here
https://leetcode.com/problems/swapping-nodes-in-a-linked-list/discuss/1911996/Python-Simple-Solution-with-Explanation
82
You are given the head of a linked list, and an integer k. Return the head of the linked list after swapping the values of the kth node from the beginning and the kth node from the end (the list is 1-indexed). Example 1: Input: head = [1,2,3,4,5], k = 2 Output: [1,4,3,2,5] Example 2: Input: head = [7,9,6,6,7,8,3,0,9,...
[Python] Simple Solution with Explanation
2,800
swapping-nodes-in-a-linked-list
0.677
zayne-siew
Medium
24,885
1,721
minimize hamming distance after swap operations
class Solution: def minimumHammingDistance(self, source: List[int], target: List[int], allowedSwaps: List[List[int]]) -> int: def gen_adjacency(): adj = {} for i in range(len(source)): adj[i] = [] for a, b in allowedSwaps: adj[a].append(b) ...
https://leetcode.com/problems/minimize-hamming-distance-after-swap-operations/discuss/1982743/Python3-solution
0
You are given two integer arrays, source and target, both of length n. You are also given an array allowedSwaps where each allowedSwaps[i] = [ai, bi] indicates that you are allowed to swap the elements at index ai and index bi (0-indexed) of array source. Note that you can swap elements at a specific pair of indices mu...
Python3 solution
45
minimize-hamming-distance-after-swap-operations
0.487
dalechoi
Medium
24,919
1,722
find minimum time to finish all jobs
class Solution: def minimumTimeRequired(self, jobs: List[int], k: int) -> int: jobs.sort(reverse=True) def fn(i): """Assign jobs to worker and find minimum time.""" nonlocal ans if i == len(jobs): ans = max(time) else: for kk...
https://leetcode.com/problems/find-minimum-time-to-finish-all-jobs/discuss/1009859/Python3-backtracking
5
You are given an integer array jobs, where jobs[i] is the amount of time it takes to complete the ith job. There are k workers that you can assign jobs to. Each job should be assigned to exactly one worker. The working time of a worker is the sum of the time it takes to complete all jobs assigned to them. Your goal is ...
[Python3] backtracking
805
find-minimum-time-to-finish-all-jobs
0.426
ye15
Hard
24,921
1,723
number of rectangles that can form the largest square
class Solution: def countGoodRectangles(self, rectangles: List[List[int]]) -> int: freq = {} for l, w in rectangles: x = min(l, w) freq[x] = 1 + freq.get(x, 0) return freq[max(freq)]
https://leetcode.com/problems/number-of-rectangles-that-can-form-the-largest-square/discuss/1020629/Python3-freq-table
3
You are given an array rectangles where rectangles[i] = [li, wi] represents the ith rectangle of length li and width wi. You can cut the ith rectangle to form a square with a side length of k if both k <= li and k <= wi. For example, if you have a rectangle [4,6], you can cut it to get a square with a side length of at...
[Python3] freq table
222
number-of-rectangles-that-can-form-the-largest-square
0.787
ye15
Easy
24,924
1,725
tuple with same product
class Solution: def tupleSameProduct(self, nums: List[int]) -> int: ans = 0 freq = {} for i in range(len(nums)): for j in range(i+1, len(nums)): key = nums[i] * nums[j] ans += freq.get(key, 0) freq[key] = 1 + freq.get(key, 0) ...
https://leetcode.com/problems/tuple-with-same-product/discuss/1020657/Python3-freq-table
31
Given an array nums of distinct positive integers, return the number of tuples (a, b, c, d) such that a * b = c * d where a, b, c, and d are elements of nums, and a != b != c != d. Example 1: Input: nums = [2,3,4,6] Output: 8 Explanation: There are 8 valid tuples: (2,6,3,4) , (2,6,4,3) , (6,2,3,4) , (6,2,4,3) (3,4,2,...
[Python3] freq table
2,100
tuple-with-same-product
0.608
ye15
Medium
24,954
1,726
largest submatrix with rearrangements
class Solution: def largestSubmatrix(self, matrix: List[List[int]]) -> int: m, n, ans = len(matrix), len(matrix[0]), 0 for j in range(n): for i in range(1, m): matrix[i][j] += matrix[i-1][j] if matrix[i][j] else 0 for i in range(m): ...
https://leetcode.com/problems/largest-submatrix-with-rearrangements/discuss/1020589/Simple-Python3-or-9-Lines-or-Beats-100-or-Detailed-Explanation
9
You are given a binary matrix matrix of size m x n, and you are allowed to rearrange the columns of the matrix in any order. Return the area of the largest submatrix within matrix where every element of the submatrix is 1 after reordering the columns optimally. Example 1: Input: matrix = [[0,0,1],[1,1,1],[1,0,1]] Out...
Simple Python3 | 9 Lines | Beats 100% | Detailed Explanation
627
largest-submatrix-with-rearrangements
0.61
sushanthsamala
Medium
24,962
1,727
cat and mouse ii
class Solution: def canMouseWin(self, grid: List[str], catJump: int, mouseJump: int) -> bool: dirs = [[1, 0], [-1, 0], [0, 1], [0, -1]] m, n = len(grid), len(grid[0]) mouse_pos = cat_pos = None available = 0 # available steps for mouse and cat # Search the start pos of mouse and cat ...
https://leetcode.com/problems/cat-and-mouse-ii/discuss/1020616/Python3-Clean-and-Commented-Top-down-DP-with-the-early-stopping-trick
48
A game is played by a cat and a mouse named Cat and Mouse. The environment is represented by a grid of size rows x cols, where each element is a wall, floor, player (Cat, Mouse), or food. Players are represented by the characters 'C'(Cat),'M'(Mouse). Floors are represented by the character '.' and can be walked on. Wal...
Python3 Clean & Commented Top-down DP with the early stopping trick
4,000
cat-and-mouse-ii
0.402
GBLin5566
Hard
24,966
1,728
find the highest altitude
class Solution(object): def largestAltitude(self, gain): """ :type gain: List[int] :rtype: int """ #initialize a variable to store the end output result = 0 #initialize a variable to keep track of the altitude at each iteration current_altitude=0 #looping throug...
https://leetcode.com/problems/find-the-highest-altitude/discuss/1223440/24ms-Python-(with-comments)
7
There is a biker going on a road trip. The road trip consists of n + 1 points at different altitudes. The biker starts his trip on point 0 with altitude equal 0. You are given an integer array gain of length n where gain[i] is the net gain in altitude between points i and i + 1 for all (0 <= i < n). Return the highest ...
24ms, Python (with comments)
575
find-the-highest-altitude
0.787
Akshar-code
Easy
24,968
1,732
minimum number of people to teach
class Solution: def minimumTeachings(self, n: int, languages: List[List[int]], friendships: List[List[int]]) -> int: m = len(languages) languages = [set(x) for x in languages] mp = {} for u, v in friendships: if not languages[u-1] &amp; languages[v-1]: ...
https://leetcode.com/problems/minimum-number-of-people-to-teach/discuss/1059885/Python3-count-properly
1
On a social network consisting of m users and some friendships between users, two users can communicate with each other if they know a common language. You are given an integer n, an array languages, and an array friendships where: There are n languages numbered 1 through n, languages[i] is the set of languages the ith...
[Python3] count properly
107
minimum-number-of-people-to-teach
0.418
ye15
Medium
25,014
1,733
decode xored permutation
class Solution: def decode(self, encoded: List[int]) -> List[int]: n = len(encoded)+1 XOR = 0 for i in range(1,n+1): XOR = XOR^i s = 0 for i in range(1,n,2): s = s^encoded[i] res = [0]*n res[0] = XOR^s for j in...
https://leetcode.com/problems/decode-xored-permutation/discuss/1031227/Python-or-Detailed-Exeplanation-by-finding-the-first-one
1
There is an integer array perm that is a permutation of the first n positive integers, where n is always odd. It was encoded into another integer array encoded of length n - 1, such that encoded[i] = perm[i] XOR perm[i + 1]. For example, if perm = [1,3,2], then encoded = [2,1]. Given the encoded array, return the origi...
Python | Detailed Exeplanation by finding the first one
111
decode-xored-permutation
0.624
jmin3
Medium
25,017
1,734
count ways to make array with product
class Solution: def waysToFillArray(self, queries: List[List[int]]) -> List[int]: # brute DP O(NK) where N is max(q[0]) and K is max(q[1]) @cache def dp(n,k): if k == 1 or n == 1: return 1 ways = 0 for factor in range(1, k+1): ...
https://leetcode.com/problems/count-ways-to-make-array-with-product/discuss/1355240/No-Maths-Just-Recursion-DP-we-can-come-up-with-in-interviews-greater-WA
1
You are given a 2D integer array, queries. For each queries[i], where queries[i] = [ni, ki], find the number of different ways you can place positive integers into an array of size ni such that the product of the integers is ki. As the number of ways may be too large, the answer to the ith query is the number of ways m...
No Maths Just Recursion DP we can come up with in interviews -> WA
326
count-ways-to-make-array-with-product
0.506
yozaam
Hard
25,020
1,735
latest time by replacing hidden digits
class Solution: def maximumTime(self, time: str) -> str: time = list(time) for i in range(len(time)): if time[i] == "?": if i == 0: time[i] = "2" if time[i+1] in "?0123" else "1" elif i == 1: time[i] = "3" if time[0] == "2" else "9" elif ...
https://leetcode.com/problems/latest-time-by-replacing-hidden-digits/discuss/1032030/Python3-if-elif
27
You are given a string time in the form of hh:mm, where some of the digits in the string are hidden (represented by ?). The valid times are those inclusively between 00:00 and 23:59. Return the latest valid time you can get from time by replacing the hidden digits. Example 1: Input: time = "2?:?0" Output: "23:50" Ex...
[Python3] if-elif
1,500
latest-time-by-replacing-hidden-digits
0.422
ye15
Easy
25,025
1,736
change minimum characters to satisfy one of three conditions
class Solution: def minCharacters(self, a: str, b: str) -> int: pa, pb = [0]*26, [0]*26 for x in a: pa[ord(x)-97] += 1 for x in b: pb[ord(x)-97] += 1 ans = len(a) - max(pa) + len(b) - max(pb) # condition 3 for i in range(25): pa[i+1] += pa[i] ...
https://leetcode.com/problems/change-minimum-characters-to-satisfy-one-of-three-conditions/discuss/1032055/Python3-scan-through-a-z-w-prefix
1
You are given two strings a and b that consist of lowercase letters. In one operation, you can change any character in a or b to any lowercase letter. Your goal is to satisfy one of the following three conditions: Every letter in a is strictly less than every letter in b in the alphabet. Every letter in b is strictly l...
[Python3] scan through a-z w/ prefix
58
change-minimum-characters-to-satisfy-one-of-three-conditions
0.352
ye15
Medium
25,042
1,737
find kth largest xor coordinate value
class Solution: def kthLargestValue(self, matrix: List[List[int]], k: int) -> int: m, n = len(matrix), len(matrix[0]) # dimensions ans = [] for i in range(m): for j in range(n): if i: matrix[i][j] ^= matrix[i-1][j] if j: matrix[i][j] ^=...
https://leetcode.com/problems/find-kth-largest-xor-coordinate-value/discuss/1032117/Python3-compute-xor-O(MNlog(MN))-or-O(MNlogK)-or-O(MN)
15
You are given a 2D matrix of size m x n, consisting of non-negative integers. You are also given an integer k. The value of coordinate (a, b) of the matrix is the XOR of all matrix[i][j] where 0 <= i <= a < m and 0 <= j <= b < n (0-indexed). Find the kth largest value (1-indexed) of all the coordinates of matrix. Exa...
[Python3] compute xor O(MNlog(MN)) | O(MNlogK) | O(MN)
936
find-kth-largest-xor-coordinate-value
0.613
ye15
Medium
25,043
1,738
building boxes
class Solution: def minimumBoxes(self, n: int) -> int: x = int((6*n)**(1/3)) if x*(x+1)*(x+2) > 6*n: x -= 1 ans = x*(x+1)//2 n -= x*(x+1)*(x+2)//6 k = 1 while n > 0: ans += 1 n -= k k += 1 return ans
https://leetcode.com/problems/building-boxes/discuss/1032104/Python3-math
12
You have a cubic storeroom where the width, length, and height of the room are all equal to n units. You are asked to place n boxes in this room where each box is a cube of unit side length. There are however some rules to placing the boxes: You can place the boxes anywhere on the floor. If box x is placed on top of th...
[Python3] math
371
building-boxes
0.519
ye15
Hard
25,050
1,739
maximum number of balls in a box
class Solution: def countBalls(self, lowLimit: int, highLimit: int) -> int: freq = defaultdict(int) for x in range(lowLimit, highLimit+1): freq[sum(int(xx) for xx in str(x))] += 1 return max(freq.values())
https://leetcode.com/problems/maximum-number-of-balls-in-a-box/discuss/1042922/Python3-freq-table
11
You are working in a ball factory where you have n balls numbered from lowLimit up to highLimit inclusive (i.e., n == highLimit - lowLimit + 1), and an infinite number of boxes numbered from 1 to infinity. Your job at this factory is to put each ball in the box with a number equal to the sum of digits of the ball's num...
[Python3] freq table
1,300
maximum-number-of-balls-in-a-box
0.739
ye15
Easy
25,056
1,742
restore the array from adjacent pairs
class Solution: def restoreArray(self, adjacentPairs: List[List[int]]) -> List[int]: graph = {} for u, v in adjacentPairs: graph.setdefault(u, []).append(v) graph.setdefault(v, []).append(u) ans = [] seen = set() stack = [next(x for x in grap...
https://leetcode.com/problems/restore-the-array-from-adjacent-pairs/discuss/1042939/Python3-graph
14
There is an integer array nums that consists of n unique elements, but you have forgotten it. However, you do remember every pair of adjacent elements in nums. You are given a 2D integer array adjacentPairs of size n - 1 where each adjacentPairs[i] = [ui, vi] indicates that the elements ui and vi are adjacent in nums. ...
[Python3] graph
1,300
restore-the-array-from-adjacent-pairs
0.687
ye15
Medium
25,076
1,743
can you eat your favorite candy on your favorite day
class Solution: def canEat(self, candiesCount: List[int], queries: List[List[int]]) -> List[bool]: prefix = [0] for x in candiesCount: prefix.append(prefix[-1] + x) # prefix sum return [prefix[t] < (day+1)*cap and day < prefix[t+1] for t, day, cap in queries]
https://leetcode.com/problems/can-you-eat-your-favorite-candy-on-your-favorite-day/discuss/1042952/Python3-greedy
6
You are given a (0-indexed) array of positive integers candiesCount where candiesCount[i] represents the number of candies of the ith type you have. You are also given a 2D array queries where queries[i] = [favoriteTypei, favoriteDayi, dailyCapi]. You play a game with the following rules: You start eating candies on da...
[Python3] greedy
279
can-you-eat-your-favorite-candy-on-your-favorite-day
0.329
ye15
Medium
25,089
1,744
palindrome partitioning iv
class Solution: def checkPartitioning(self, s: str) -> bool: mp = {} for i in range(2*len(s)-1): lo, hi = i//2, (i+1)//2 while 0 <= lo <= hi < len(s) and s[lo] == s[hi]: mp.setdefault(lo, set()).add(hi) lo -= 1 hi += 1 ...
https://leetcode.com/problems/palindrome-partitioning-iv/discuss/1042964/Python3-dp
10
Given a string s, return true if it is possible to split the string s into three non-empty palindromic substrings. Otherwise, return false. A string is said to be palindrome if it the same string when reversed. Example 1: Input: s = "abcbdd" Output: true Explanation: "abcbdd" = "a" + "bcb" + "dd", and all three subst...
[Python3] dp
725
palindrome-partitioning-iv
0.459
ye15
Hard
25,090
1,745
sum of unique elements
class Solution: def sumOfUnique(self, nums: List[int]) -> int: hashmap = {} for i in nums: if i in hashmap.keys(): hashmap[i] += 1 else: hashmap[i] = 1 sum = 0 for k, v in hashmap.items(): if v == 1: sum += k ...
https://leetcode.com/problems/sum-of-unique-elements/discuss/1103188/Runtime-97-or-Python-easy-hashmap-solution
19
You are given an integer array nums. The unique elements of an array are the elements that appear exactly once in the array. Return the sum of all the unique elements of nums. Example 1: Input: nums = [1,2,3,2] Output: 4 Explanation: The unique elements are [1,3], and the sum is 4. Example 2: Input: nums = [1,1,1,1,1...
Runtime 97% | Python easy hashmap solution
1,900
sum-of-unique-elements
0.757
vanigupta20024
Easy
25,095
1,748
maximum absolute sum of any subarray
class Solution: def maxAbsoluteSum(self, nums: List[int]) -> int: ans = mx = mn = 0 for x in nums: mx = max(mx + x, 0) mn = min(mn + x, 0) ans = max(ans, mx, -mn) return ans
https://leetcode.com/problems/maximum-absolute-sum-of-any-subarray/discuss/1056653/Python3-Kadane's-algo
10
You are given an integer array nums. The absolute sum of a subarray [numsl, numsl+1, ..., numsr-1, numsr] is abs(numsl + numsl+1 + ... + numsr-1 + numsr). Return the maximum absolute sum of any (possibly empty) subarray of nums. Note that abs(x) is defined as follows: If x is a negative integer, then abs(x) = -x. If x ...
[Python3] Kadane's algo
329
maximum-absolute-sum-of-any-subarray
0.583
ye15
Medium
25,141
1,749
minimum length of string after deleting similar ends
class Solution: def minimumLength(self, s: str) -> int: dd = deque(s) while len(dd) >= 2 and dd[0] == dd[-1]: ch = dd[0] while dd and dd[0] == ch: dd.popleft() while dd and dd[-1] == ch: dd.pop() return len(dd)
https://leetcode.com/problems/minimum-length-of-string-after-deleting-similar-ends/discuss/1056664/Python3-3-approaches
2
Given a string s consisting only of characters 'a', 'b', and 'c'. You are asked to apply the following algorithm on the string any number of times: Pick a non-empty prefix from the string s where all the characters in the prefix are equal. Pick a non-empty suffix from the string s where all the characters in this suffi...
[Python3] 3 approaches
74
minimum-length-of-string-after-deleting-similar-ends
0.436
ye15
Medium
25,156
1,750
maximum number of events that can be attended ii
class Solution: def maxValue(self, events: List[List[int]], k: int) -> int: # The number of events n = len(events) # Sort the events in chronological order events.sort() # k is the number of events we can attend # end is the last event we attended's ...
https://leetcode.com/problems/maximum-number-of-events-that-can-be-attended-ii/discuss/1103634/Python3-(DP)-Simple-Solution-Explained
11
You are given an array of events where events[i] = [startDayi, endDayi, valuei]. The ith event starts at startDayi and ends at endDayi, and if you attend this event, you will receive a value of valuei. You are also given an integer k which represents the maximum number of events you can attend. You can only attend one ...
[Python3] (DP) Simple Solution Explained
637
maximum-number-of-events-that-can-be-attended-ii
0.56
scornz
Hard
25,167
1,751
check if array is sorted and rotated
class Solution: def check(self, nums: List[int]) -> bool: i = 0 while i<len(nums)-1: if nums[i]>nums[i+1]: break # used to find the rotated position i+=1 rotated = nums[i+1:]+nums[:i+1] for i,e in enumerate(rotated): if i<len(rotated)-1...
https://leetcode.com/problems/check-if-array-is-sorted-and-rotated/discuss/1053871/Python-Slicing-(easy-to-understand)
12
Given an array nums, return true if the array was originally sorted in non-decreasing order, then rotated some number of positions (including zero). Otherwise, return false. There may be duplicates in the original array. Note: An array A rotated by x positions results in an array B of the same length such that A[i] == ...
Python - Slicing (easy to understand)
966
check-if-array-is-sorted-and-rotated
0.493
qwe9
Easy
25,172
1,752
maximum score from removing stones
class Solution: def maximumScore(self, a: int, b: int, c: int) -> int: a, b, c = sorted((a, b, c)) if a + b < c: return a + b return (a + b + c)//2
https://leetcode.com/problems/maximum-score-from-removing-stones/discuss/1053645/Python3-math
15
You are playing a solitaire game with three piles of stones of sizes a, b, and c respectively. Each turn you choose two different non-empty piles, take one stone from each, and add 1 point to your score. The game stops when there are fewer than two non-empty piles (meaning there are no more available moves). Given thre...
[Python3] math
745
maximum-score-from-removing-stones
0.662
ye15
Medium
25,209
1,753
largest merge of two strings
class Solution: def largestMerge(self, word1: str, word2: str) -> str: ans = [] i1 = i2 = 0 while i1 < len(word1) and i2 < len(word2): if word1[i1:] > word2[i2:]: ans.append(word1[i1]) i1 += 1 else: ans.append(word2[i...
https://leetcode.com/problems/largest-merge-of-two-strings/discuss/1053605/Python3-greedy
6
You are given two strings word1 and word2. You want to construct a string merge in the following way: while either word1 or word2 are non-empty, choose one of the following options: If word1 is non-empty, append the first character in word1 to merge and delete it from word1. For example, if word1 = "abc" and merge = "d...
[Python3] greedy
251
largest-merge-of-two-strings
0.451
ye15
Medium
25,223
1,754
closest subsequence sum
class Solution: def minAbsDifference(self, nums: List[int], goal: int) -> int: def fn(nums): ans = {0} for x in nums: ans |= {x + y for y in ans} return ans nums0 = sorted(fn(nums[:len(nums)//2])) ans = inf ...
https://leetcode.com/problems/closest-subsequence-sum/discuss/1053790/Python3-divide-in-half
28
You are given an integer array nums and an integer goal. You want to choose a subsequence of nums such that the sum of its elements is the closest possible to goal. That is, if the sum of the subsequence's elements is sum, then you want to minimize the absolute difference abs(sum - goal). Return the minimum possible va...
[Python3] divide in half
1,400
closest-subsequence-sum
0.364
ye15
Hard
25,230
1,755
minimum changes to make alternating binary string
class Solution: def minOperations(self, s: str) -> int: count = 0 count1 = 0 for i in range(len(s)): if i % 2 == 0: if s[i] == '1': count += 1 if s[i] == '0': count1 += 1 else: if ...
https://leetcode.com/problems/minimum-changes-to-make-alternating-binary-string/discuss/1437401/Python3-solution-or-O(n)-or-Explained
10
You are given a string s consisting only of the characters '0' and '1'. In one operation, you can change any '0' to '1' or vice versa. The string is called alternating if no two adjacent characters are equal. For example, the string "010" is alternating, while the string "0100" is not. Return the minimum number of oper...
Python3 solution | O(n) | Explained
425
minimum-changes-to-make-alternating-binary-string
0.583
FlorinnC1
Easy
25,233
1,758
count number of homogenous substrings
class Solution: def countHomogenous(self, s: str) -> int: res, count, n = 0, 1, len(s) for i in range(1,n): if s[i]==s[i-1]: count+=1 else: if count>1: res+=(count*(count-1)//2) count=1 if count>1...
https://leetcode.com/problems/count-number-of-homogenous-substrings/discuss/1064598/Python-one-pass-with-explanation
6
Given a string s, return the number of homogenous substrings of s. Since the answer may be too large, return it modulo 109 + 7. A string is homogenous if all the characters of the string are the same. A substring is a contiguous sequence of characters within a string. Example 1: Input: s = "abbcccaa" Output: 13 Expla...
Python - one pass - with explanation
353
count-number-of-homogenous-substrings
0.48
ajith6198
Medium
25,256
1,759
minimum limit of balls in a bag
class Solution: def minimumSize(self, nums: List[int], maxOperations: int) -> int: lo, hi = 1, 1_000_000_000 while lo < hi: mid = lo + hi >> 1 if sum((x-1)//mid for x in nums) <= maxOperations: hi = mid else: lo = mid + 1 return lo
https://leetcode.com/problems/minimum-limit-of-balls-in-a-bag/discuss/1064572/Python3-binary-search
2
You are given an integer array nums where the ith bag contains nums[i] balls. You are also given an integer maxOperations. You can perform the following operation at most maxOperations times: Take any bag of balls and divide it into two new bags with a positive number of balls. For example, a bag of 5 balls can become ...
[Python3] binary search
238
minimum-limit-of-balls-in-a-bag
0.603
ye15
Medium
25,271
1,760
minimum degree of a connected trio in a graph
class Solution: def minTrioDegree(self, n: int, edges: List[List[int]]) -> int: graph = [[False]*n for _ in range(n)] degree = [0]*n for u, v in edges: graph[u-1][v-1] = graph[v-1][u-1] = True degree[u-1] += 1 degree[v-1] += 1 an...
https://leetcode.com/problems/minimum-degree-of-a-connected-trio-in-a-graph/discuss/1065724/Python3-brute-force
6
You are given an undirected graph. You are given an integer n which is the number of nodes in the graph and an array edges, where each edges[i] = [ui, vi] indicates that there is an undirected edge between ui and vi. A connected trio is a set of three nodes where there is an edge between every pair of them. The degree ...
[Python3] brute-force
389
minimum-degree-of-a-connected-trio-in-a-graph
0.417
ye15
Hard
25,276
1,761
longest nice substring
class Solution: def longestNiceSubstring(self, s: str) -> str: ans = "" for i in range(len(s)): for ii in range(i+1, len(s)+1): if all(s[k].swapcase() in s[i:ii] for k in range(i, ii)): ans = max(ans, s[i:ii], key=len) return ans
https://leetcode.com/problems/longest-nice-substring/discuss/1074546/Python3-brute-force-and-divide-and-conquer
65
A string s is nice if, for every letter of the alphabet that s contains, it appears both in uppercase and lowercase. For example, "abABB" is nice because 'A' and 'a' appear, and 'B' and 'b' appear. However, "abA" is not because 'b' appears, but 'B' does not. Given a string s, return the longest substring of s that is n...
[Python3] brute-force & divide and conquer
4,800
longest-nice-substring
0.616
ye15
Easy
25,279
1,763
form array by concatenating subarrays of another array
class Solution: def canChoose(self, groups: List[List[int]], nums: List[int]) -> bool: i = 0 for grp in groups: for ii in range(i, len(nums)): if nums[ii:ii+len(grp)] == grp: i = ii + len(grp) break else: return False...
https://leetcode.com/problems/form-array-by-concatenating-subarrays-of-another-array/discuss/1074555/Python3-check-group-one-by-one
28
You are given a 2D integer array groups of length n. You are also given an integer array nums. You are asked if you can choose n disjoint subarrays from the array nums such that the ith subarray is equal to groups[i] (0-indexed), and if i > 0, the (i-1)th subarray appears before the ith subarray in nums (i.e. the subar...
[Python3] check group one-by-one
1,300
form-array-by-concatenating-subarrays-of-another-array
0.527
ye15
Medium
25,297
1,764
map of highest peak
class Solution: def highestPeak(self, isWater: List[List[int]]) -> List[List[int]]: m, n = len(isWater), len(isWater[0]) # dimensions queue = [(i, j) for i in range(m) for j in range(n) if isWater[i][j]] ht = 0 ans = [[0]*n for _ in range(m)] seen = set(queue) ...
https://leetcode.com/problems/map-of-highest-peak/discuss/1074561/Python3-bfs
7
You are given an integer matrix isWater of size m x n that represents a map of land and water cells. If isWater[i][j] == 0, cell (i, j) is a land cell. If isWater[i][j] == 1, cell (i, j) is a water cell. You must assign each cell a height in a way that follows these rules: The height of each cell must be non-negative. ...
[Python3] bfs
349
map-of-highest-peak
0.604
ye15
Medium
25,304
1,765
tree of coprimes
class Solution: def getCoprimes(self, nums: List[int], edges: List[List[int]]) -> List[int]: tree = {} # tree as adjacency list for u, v in edges: tree.setdefault(u, []).append(v) tree.setdefault(v, []).append(u) ans = [-1]*len(nums) path = {} # val...
https://leetcode.com/problems/tree-of-coprimes/discuss/1074565/Python3-dfs
10
There is a tree (i.e., a connected, undirected graph that has no cycles) consisting of n nodes numbered from 0 to n - 1 and exactly n - 1 edges. Each node has a value associated with it, and the root of the tree is node 0. To represent this tree, you are given an integer array nums and a 2D array edges. Each nums[i] re...
[Python3] dfs
702
tree-of-coprimes
0.392
ye15
Hard
25,312
1,766