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] - arr[i + 1]) return len(set(dif)) == 1 for i , j in zip(l , r): ans.append(find_diffs(nums[i:j + 1])) return ans
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, 7, 7, 7 3, -1, -5, -9 The following sequence is not arithmetic: 1, 1, 2, 5, 7 You are given an array of n integers, nums, and two arrays of m integers each, l and r, representing the m range queries, where the ith query is the range [l[i], r[i]]. All the arrays are 0-indexed. Return a list of boolean elements answer, where answer[i] is true if the subarray nums[l[i]], nums[l[i]+1], ... , nums[r[i]] can be rearranged to form an arithmetic sequence, and false otherwise. Example 1: Input: nums = [4,6,5,9,3,7], l = [0,0,2], r = [2,3,5] Output: [true,false,true] Explanation: In the 0th query, the subarray is [4,6,5]. This can be rearranged as [6,5,4], which is an arithmetic sequence. In the 1st query, the subarray is [4,6,5,9]. This cannot be rearranged as an arithmetic sequence. In the 2nd query, the subarray is [5,9,3,7]. This can be rearranged as [3,5,7,9], which is an arithmetic sequence. Example 2: Input: nums = [-12,-9,-3,-12,-6,15,20,-25,-20,-15,-10], l = [0,1,6,4,8,7], r = [4,4,9,7,9,10] Output: [false,true,false,false,true,true] Constraints: n == nums.length m == l.length m == r.length 2 <= n <= 500 1 <= m <= 500 0 <= l[i] < r[i] < n -105 <= nums[i] <= 105
[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 = {} # new dictionary for (i, j), h in queue.items(): if i == m-1 and j == n-1: ans = min(ans, h) for ii, jj in (i-1, j), (i, j-1), (i, j+1), (i+1, j): if 0 <= ii < m and 0 <= jj < n: hh = max(h, abs(heights[i][j] - heights[ii][jj])) if hh < seen.get((ii, jj), inf): seen[(ii, jj)] = hh newq[(ii, jj)] = hh queue = newq return ans
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 up, down, left, or right, and you wish to find a route that requires the minimum effort. A route's effort is the maximum absolute difference in heights between two consecutive cells of the route. Return the minimum effort required to travel from the top-left cell to the bottom-right cell. Example 1: Input: heights = [[1,2,2],[3,8,2],[5,3,5]] Output: 2 Explanation: The route of [1,3,5,3,5] has a maximum absolute difference of 2 in consecutive cells. This is better than the route of [1,2,2,2,5], where the maximum absolute difference is 3. Example 2: Input: heights = [[1,2,3],[3,8,4],[5,3,5]] Output: 1 Explanation: The route of [1,2,3,4,5] has a maximum absolute difference of 1 in consecutive cells, which is better than route [1,3,5,3,5]. Example 3: Input: heights = [[1,2,1,1,1],[1,2,1,2,1],[1,2,1,2,1],[1,2,1,2,1],[1,1,1,2,1]] Output: 0 Explanation: This route does not require any effort. Constraints: rows == heights.length columns == heights[i].length 1 <= rows, columns <= 100 1 <= heights[i][j] <= 106
[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((i, j)) def find(p): """Find root of p.""" if p != parent[p]: parent[p] = find(parent[p]) return parent[p] rank = [0]*(m+n) ans = [[0]*n for _ in range(m)] for k in sorted(mp): # from minimum to maximum parent = list(range(m+n)) for i, j in mp[k]: ii, jj = find(i), find(m+j) # find parent[ii] = jj # union rank[jj] = max(rank[ii], rank[jj]) # max rank seen = set() for i, j in mp[k]: ii = find(i) if ii not in seen: rank[ii] += 1 seen.add(ii) rank[i] = rank[m+j] = ans[i][j] = rank[ii] return ans
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 row or column, then: If p < q then rank(p) < rank(q) If p == q then rank(p) == rank(q) If p > q then rank(p) > rank(q) The rank should be as small as possible. The test cases are generated so that answer is unique under the given rules. Example 1: Input: matrix = [[1,2],[3,4]] Output: [[1,2],[2,3]] Explanation: The rank of matrix[0][0] is 1 because it is the smallest integer in its row and column. The rank of matrix[0][1] is 2 because matrix[0][1] > matrix[0][0] and matrix[0][0] is rank 1. The rank of matrix[1][0] is 2 because matrix[1][0] > matrix[0][0] and matrix[0][0] is rank 1. The rank of matrix[1][1] is 3 because matrix[1][1] > matrix[0][1], matrix[1][1] > matrix[1][0], and both matrix[0][1] and matrix[1][0] are rank 2. Example 2: Input: matrix = [[7,7],[7,7]] Output: [[1,1],[1,1]] Example 3: Input: matrix = [[20,-21,14],[-19,4,19],[22,-47,24],[-19,4,19]] Output: [[4,2,3],[1,3,4],[5,1,6],[1,3,4]] Constraints: m == matrix.length n == matrix[i].length 1 <= m, n <= 500 -109 <= matrix[row][col] <= 109
[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 frequency of 2, and '2' has a frequency of 3. Example 2: Input: nums = [2,3,1,3,2] Output: [1,3,3,2,2] Explanation: '2' and '3' both have a frequency of 2, so they are sorted in decreasing order. Example 3: Input: nums = [-1,1,-6,4,5,-6,1,4,1] Output: [5,-1,4,4,-6,-6,1,1,1] Constraints: 1 <= nums.length <= 100 -100 <= nums[i] <= 100
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 that points on the edge of a vertical area are not considered included in the area. Example 1: Input: points = [[8,7],[9,9],[7,4],[9,7]] Output: 1 Explanation: Both the red and the blue area are optimal. Example 2: Input: points = [[3,1],[9,0],[1,0],[1,4],[5,3],[8,8]] Output: 3 Constraints: n == points.length 2 <= n <= 105 points[i].length == 2 0 <= xi, yi <= 109
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 fn(i-1, j-1, k) + (k==0) else: return 0 if k == 0 else 1 + fn(i-1, j-1, 0) return sum(fn(i, j, 1) for i in range(m) for j in range(n))
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. For example, the underlined substrings in "computer" and "computation" only differ by the 'e'/'a', so this is a valid way. Return the number of substrings that satisfy the condition above. A substring is a contiguous sequence of characters within a string. Example 1: Input: s = "aba", t = "baba" Output: 6 Explanation: The following are the pairs of substrings from s and t that differ by exactly 1 character: ("aba", "baba") ("aba", "baba") ("aba", "baba") ("aba", "baba") ("aba", "baba") ("aba", "baba") The underlined portions are the substrings that are chosen from s and t. Example 2: Input: s = "ab", t = "bb" Output: 3 Explanation: The following are the pairs of substrings from s and t that differ by 1 character: ("ab", "bb") ("ab", "bb") ("ab", "bb") The underlined portions are the substrings that are chosen from s and t. Constraints: 1 <= s.length, t.length <= 100 s and t consist of lowercase English letters only.
[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 of ways to form target[i:] w/ col k.""" if i == len(target): return 1 if k == len(words[0]): return 0 return freq[k][target[i]]*fn(i+1, k+1) + fn(i, k+1) return fn(0, 0) % 1_000_000_007
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] = words[j][k]. Once you use the kth character of the jth string of words, you can no longer use the xth character of any string in words where x <= k. In other words, all characters to the left of or at index k become unusuable for every string. Repeat the process until you form the string target. Notice that you can use multiple characters from the same string in words provided the conditions above are met. Return the number of ways to form target from words. Since the answer may be too large, return it modulo 109 + 7. Example 1: Input: words = ["acca","bbbb","caca"], target = "aba" Output: 6 Explanation: There are 6 ways to form target. "aba" -> index 0 ("acca"), index 1 ("bbbb"), index 3 ("caca") "aba" -> index 0 ("acca"), index 2 ("bbbb"), index 3 ("caca") "aba" -> index 0 ("acca"), index 1 ("bbbb"), index 3 ("acca") "aba" -> index 0 ("acca"), index 2 ("bbbb"), index 3 ("acca") "aba" -> index 1 ("caca"), index 2 ("bbbb"), index 3 ("acca") "aba" -> index 1 ("caca"), index 2 ("bbbb"), index 3 ("caca") Example 2: Input: words = ["abba","baab"], target = "bab" Output: 4 Explanation: There are 4 ways to form target. "bab" -> index 0 ("baab"), index 1 ("baab"), index 2 ("abba") "bab" -> index 0 ("baab"), index 1 ("baab"), index 3 ("baab") "bab" -> index 0 ("baab"), index 2 ("baab"), index 3 ("baab") "bab" -> index 1 ("abba"), index 2 ("baab"), index 3 ("baab") Constraints: 1 <= words.length <= 1000 1 <= words[i].length <= 1000 All strings in words have the same length. 1 <= target.length <= 1000 words[i] and target contain only lowercase English letters.
[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 form the array arr from pieces. Otherwise, return false. Example 1: Input: arr = [15,88], pieces = [[88],[15]] Output: true Explanation: Concatenate [15] then [88] Example 2: Input: arr = [49,18,16], pieces = [[16,18,49]] Output: false Explanation: Even though the numbers match, we cannot reorder pieces[0]. Example 3: Input: arr = [91,4,64,78], pieces = [[78],[4,64],[91]] Output: true Explanation: Concatenate [91] then [4,64] then [78] Constraints: 1 <= pieces.length <= arr.length <= 100 sum(pieces[i].length) == arr.length 1 <= pieces[i].length <= arr.length 1 <= arr[i], pieces[i][j] <= 100 The integers in arr are distinct. The integers in pieces are distinct (i.e., If we flatten pieces in a 1D array, all the integers in this array are distinct).
[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] return dp[n][5]
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 strings that consist of vowels only are ["a","e","i","o","u"]. Example 2: Input: n = 2 Output: 15 Explanation: The 15 sorted strings that consist of vowels only are ["aa","ae","ai","ao","au","ee","ei","eo","eu","ii","io","iu","oo","ou","uu"]. Note that "ea" is not a valid string since 'e' comes after 'a' in the alphabet. Example 3: Input: n = 33 Output: 66045 Constraints: 1 <= n <= 50
✅ 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_heap = [] n = len(heights) for i in range(n-1): climb = heights[i+1] - heights[i] if climb <= 0: continue # we need to use a ladder or some bricks, always take the ladder at first if climb > 0: heapq.heappush(min_heap, climb) # ladders are all in used, find the current shortest climb to use bricks instead! if len(min_heap) > ladders: # find the current shortest climb to use bricks brick_need = heapq.heappop(min_heap) bricks -= brick_need if bricks < 0: return i return n-1
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 than or equal to the next building's height, you do not need a ladder or bricks. If the current building's height is less than the next building's height, you can either use one ladder or (h[i+1] - h[i]) bricks. Return the furthest building index (0-indexed) you can reach if you use the given ladders and bricks optimally. Example 1: Input: heights = [4,2,7,6,9,14,12], bricks = 5, ladders = 1 Output: 4 Explanation: Starting at building 0, you can follow these steps: - Go to building 1 without using ladders nor bricks since 4 >= 2. - Go to building 2 using 5 bricks. You must use either bricks or ladders because 2 < 7. - Go to building 3 without using ladders nor bricks since 7 >= 6. - Go to building 4 using your only ladder. You must use either bricks or ladders because 6 < 9. It is impossible to go beyond building 4 because you do not have any more bricks or ladders. Example 2: Input: heights = [4,12,2,7,3,18,20,3,19], bricks = 10, ladders = 2 Output: 7 Example 3: Input: heights = [14,3,19,3], bricks = 17, ladders = 0 Output: 3 Constraints: 1 <= heights.length <= 105 1 <= heights[i] <= 106 0 <= bricks <= 109 0 <= ladders <= heights.length
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" n -= 1 else: ans += "V" m -= 1 k -= kk return ans + m*"V"
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), or 'V', meaning move vertically (go down). Multiple instructions will lead Bob to destination. For example, if destination is (2, 3), both "HHHVV" and "HVHVH" are valid instructions. However, Bob is very picky. Bob has a lucky number k, and he wants the kth lexicographically smallest instructions that will lead him to destination. k is 1-indexed. Given an integer array destination and an integer k, return the kth lexicographically smallest instructions that will take Bob to destination. Example 1: Input: destination = [2,3], k = 1 Output: "HHHVV" Explanation: All the instructions that reach (2, 3) in lexicographic order are as follows: ["HHHVV", "HHVHV", "HHVVH", "HVHHV", "HVHVH", "HVVHH", "VHHHV", "VHHVH", "VHVHH", "VVHHH"]. Example 2: Input: destination = [2,3], k = 2 Output: "HHVHV" Example 3: Input: destination = [2,3], k = 3 Output: "HHVVH" Constraints: destination.length == 2 1 <= row, column <= 15 1 <= k <= nCr(row + column, row), where nCr(a, b) denotes a choose b.
[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, 13, 14, 14, 14, 14, 15, 15, 18, 18, 18, 18, 18, 18, 18, 18, 19, 19, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21] return max_nums[n]
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: 3 Explanation: According to the given rules: nums[0] = 0 nums[1] = 1 nums[(1 * 2) = 2] = nums[1] = 1 nums[(1 * 2) + 1 = 3] = nums[1] + nums[2] = 1 + 1 = 2 nums[(2 * 2) = 4] = nums[2] = 1 nums[(2 * 2) + 1 = 5] = nums[2] + nums[3] = 1 + 2 = 3 nums[(3 * 2) = 6] = nums[3] = 2 nums[(3 * 2) + 1 = 7] = nums[3] + nums[4] = 2 + 1 = 3 Hence, nums = [0,1,1,2,1,3,2,3], and the maximum is max(0,1,1,2,1,3,2,3) = 3. Example 2: Input: n = 2 Output: 1 Explanation: According to the given rules, nums = [0,1,1]. The maximum is max(0,1,1) = 1. Example 3: Input: n = 3 Output: 2 Explanation: According to the given rules, nums = [0,1,1,2]. The maximum is max(0,1,1,2) = 2. Constraints: 0 <= n <= 100
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 += 1 if k: seen.add(k) return 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", the frequency of 'a' is 2, while the frequency of 'b' is 1. Example 1: Input: s = "aab" Output: 0 Explanation: s is already good. Example 2: Input: s = "aaabbbcc" Output: 2 Explanation: You can delete two 'b's resulting in the good string "aaabcc". Another way it to delete one 'b' and one 'c' resulting in the good string "aaabbc". Example 3: Input: s = "ceabaacb" Output: 2 Explanation: You can delete both 'c's resulting in the good string "eabaab". Note that we only care about characters that are still in the string at the end (i.e. frequency of 0 is ignored). Constraints: 1 <= s.length <= 105 s contains only lowercase English letters.
[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*(inventory[i] - inventory[i+1]) < orders: ans += k*(inventory[i] + inventory[i+1] + 1)*(inventory[i] - inventory[i+1])//2 # arithmic sum orders -= k*(inventory[i] - inventory[i+1]) else: q, r = divmod(orders, k) ans += k*(2*inventory[i] - q + 1) * q//2 + r*(inventory[i] - q) return ans % 1_000_000_007 k += 1
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 pay 6 for the first yellow ball. After the transaction, there are only 5 yellow balls left, so the next yellow ball is then valued at 5 (i.e., the value of the balls decreases as you sell more to the customer). You are given an integer array, inventory, where inventory[i] represents the number of balls of the ith color that you initially own. You are also given an integer orders, which represents the total number of balls that the customer wants. You can sell the balls in any order. Return the maximum total value that you can attain after selling orders colored balls. As the answer may be too large, return it modulo 109 + 7. Example 1: Input: inventory = [2,5], orders = 4 Output: 14 Explanation: Sell the 1st color 1 time (2) and the 2nd color 3 times (5 + 4 + 3). The maximum total value is 2 + 5 + 4 + 3 = 14. Example 2: Input: inventory = [3,5], orders = 6 Output: 19 Explanation: Sell the 1st color 2 times (3 + 2) and the 2nd color 4 times (5 + 4 + 3 + 2). The maximum total value is 3 + 2 + 5 + 4 + 3 + 2 = 19. Constraints: 1 <= inventory.length <= 105 1 <= inventory[i] <= 109 1 <= orders <= min(sum(inventory[i]), 109)
[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(data[i + 1: i + 1 + abs(k)])) if 0 > k: return result[k - 1:] + result[:k - 1] return result
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, replace the ith number with the sum of the previous k numbers. If k == 0, replace the ith number with 0. As code is circular, the next element of code[n-1] is code[0], and the previous element of code[0] is code[n-1]. Given the circular array code and an integer key k, return the decrypted code to defuse the bomb! Example 1: Input: code = [5,7,1,4], k = 3 Output: [12,10,16,13] Explanation: Each number is replaced by the sum of the next 3 numbers. The decrypted code is [7+1+4, 1+4+5, 4+5+7, 5+7+1]. Notice that the numbers wrap around. Example 2: Input: code = [1,2,3,4], k = 0 Output: [0,0,0,0] Explanation: When k is zero, the numbers are replaced by 0. Example 3: Input: code = [2,4,9,3], k = -2 Output: [12,5,6,13] Explanation: The decrypted code is [3+9, 2+3, 4+2, 9+4]. Notice that the numbers wrap around again. If k is negative, the sum is of the previous numbers. Constraints: n == code.length 1 <= n <= 100 1 <= code[i] <= 100 -(n - 1) <= k <= n - 1
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 'a' # to end with 'b', need to delete the current 'a' from previous ending with 'b' end_b += 1 else: # to end with 'a', need to delete the current 'b' from previous ending with 'a' # to end with 'b', nothing to do, so just pick smaller of end_a, end_b end_a, end_b = end_a+1, min(end_a, end_b) return min(end_a, end_b)
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 = "aababbab" Output: 2 Explanation: You can either: Delete the characters at 0-indexed positions 2 and 6 ("aababbab" -> "aaabbb"), or Delete the characters at 0-indexed positions 3 and 6 ("aababbab" -> "aabbbb"). Example 2: Input: s = "bbaaaaabb" Output: 2 Explanation: The only solution is to delete the first two characters. Constraints: 1 <= s.length <= 105 s[i] is 'a' or 'b'.
[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: continue if p==x: return s q.append((p+a,s+1,False)) if not isb: q.append((p-b,s+1,True)) seen.add((p,isb)) return -1
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 forbidden positions. The bug may jump forward beyond its home, but it cannot jump to positions numbered with negative integers. Given an array of integers forbidden, where forbidden[i] means that the bug cannot jump to the position forbidden[i], and integers a, b, and x, return the minimum number of jumps needed for the bug to reach its home. If there is no possible sequence of jumps that lands the bug on position x, return -1. Example 1: Input: forbidden = [14,4,18,1,15], a = 3, b = 15, x = 9 Output: 3 Explanation: 3 jumps forward (0 -> 3 -> 6 -> 9) will get the bug home. Example 2: Input: forbidden = [8,3,16,6,12,20], a = 15, b = 13, x = 11 Output: -1 Example 3: Input: forbidden = [1,6,2,14,5,17,4], a = 16, b = 9, x = 7 Output: 2 Explanation: One jump forward (0 -> 16) then one jump backward (16 -> 7) will get the bug home. Constraints: 1 <= forbidden.length <= 1000 1 <= a, b, forbidden[i] <= 2000 0 <= x <= 2000 All the elements in forbidden are distinct. Position x is not forbidden.
📌📌 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): """Return True if possible to distribute quantity[i:] to remaining.""" if i == len(quantity): return True seen = set() for k in range(len(vals)): if vals[k] >= quantity[i] and vals[k] not in seen: seen.add(vals[k]) # pruning - unqiue values vals[k] -= quantity[i] if fn(i+1): return True vals[k] += quantity[i] # backtracking return fn(0)
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 exactly quantity[i] integers, The integers the ith customer gets are all equal, and Every customer is satisfied. Return true if it is possible to distribute nums according to the above conditions. Example 1: Input: nums = [1,2,3,4], quantity = [2] Output: false Explanation: The 0th customer cannot be given two different integers. Example 2: Input: nums = [1,2,3,3], quantity = [2] Output: true Explanation: The 0th customer is given [3,3]. The integers [1,2] are not used. Example 3: Input: nums = [1,1,2,2], quantity = [2,2] Output: true Explanation: The 0th customer is given [1,1], and the 1st customer is given [2,2]. Constraints: n == nums.length 1 <= n <= 105 1 <= nums[i] <= 1000 m == quantity.length 1 <= m <= 10 1 <= quantity[i] <= 105 There are at most 50 unique values in nums.
[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. For example, aacabb -> bbcbaa (all a's turn into b's, and all b's turn into a's) You can use the operations on either string as many times as necessary. Given two strings, word1 and word2, return true if word1 and word2 are close, and false otherwise. Example 1: Input: word1 = "abc", word2 = "bca" Output: true Explanation: You can attain word2 from word1 in 2 operations. Apply Operation 1: "abc" -> "acb" Apply Operation 1: "acb" -> "bca" Example 2: Input: word1 = "a", word2 = "aa" Output: false Explanation: It is impossible to attain word2 from word1, or vice versa, in any number of operations. Example 3: Input: word1 = "cabbba", word2 = "abbccc" Output: true Explanation: You can attain word2 from word1 in 3 operations. Apply Operation 1: "cabbba" -> "caabbb" Apply Operation 2: "caabbb" -> "baaccc" Apply Operation 2: "baaccc" -> "abbccc" Constraints: 1 <= word1.length, word2.length <= 105 word1 and word2 contain only lowercase English letters.
[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): x -= num if x in mp and mp[x] + i <= len(nums): ans = min(ans, i + mp[x]) return ans if ans < inf else -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 possible, otherwise, return -1. Example 1: Input: nums = [1,1,4,2,3], x = 5 Output: 2 Explanation: The optimal solution is to remove the last two elements to reduce x to zero. Example 2: Input: nums = [5,6,7,8,9], x = 4 Output: -1 Example 3: Input: nums = [3,2,20,1,1,3], x = 10 Output: 5 Explanation: The optimal solution is to remove the last three elements and the first two elements (5 operations in total) to reduce x to zero. Constraints: 1 <= nums.length <= 105 1 <= nums[i] <= 104 1 <= x <= 109
[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 fn(prev, i+1, 0, intro, extro) if intro == extro == 0: return 0 prev0 = prev[:j] + (0,) + prev[j+1:] ans = fn(prev0, i, j+1, intro, extro) if intro: val = 120 if i and prev[j]: # neighbor from above val -= 30 if prev[j] == 1: val -= 30 else: val += 20 if j and prev[j-1]: # neighbor from left val -= 30 if prev[j-1] == 1: val -= 30 else: val += 20 prev0 = prev[:j] + (1,) + prev[j+1:] ans = max(ans, val + fn(prev0, i, j+1, intro-1, extro)) if extro: val = 40 if i and prev[j]: val += 20 if prev[j] == 1: val -= 30 else: val += 20 if j and prev[j-1]: val += 20 if prev[j-1] == 1: val -= 30 else: val += 20 prev0 = prev[:j] + (2,) + prev[j+1:] ans = max(ans, val + fn(prev0, i, j+1, intro, extro-1)) return ans return fn((0,)*n, 0, 0, introvertsCount, extrovertsCount)
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 grid cell. Note that you do not have to have all the people living in the grid. The happiness of each person is calculated as follows: Introverts start with 120 happiness and lose 30 happiness for each neighbor (introvert or extrovert). Extroverts start with 40 happiness and gain 20 happiness for each neighbor (introvert or extrovert). Neighbors live in the directly adjacent cells north, east, south, and west of a person's cell. The grid happiness is the sum of each person's happiness. Return the maximum possible grid happiness. Example 1: Input: m = 2, n = 3, introvertsCount = 1, extrovertsCount = 2 Output: 240 Explanation: Assume the grid is 1-indexed with coordinates (row, column). We can put the introvert in cell (1,1) and put the extroverts in cells (1,3) and (2,3). - Introvert at (1,1) happiness: 120 (starting happiness) - (0 * 30) (0 neighbors) = 120 - Extrovert at (1,3) happiness: 40 (starting happiness) + (1 * 20) (1 neighbor) = 60 - Extrovert at (2,3) happiness: 40 (starting happiness) + (1 * 20) (1 neighbor) = 60 The grid happiness is 120 + 60 + 60 = 240. The above figure shows the grid in this example with each person's happiness. The introvert stays in the light green cell while the extroverts live on the light purple cells. Example 2: Input: m = 3, n = 1, introvertsCount = 2, extrovertsCount = 1 Output: 260 Explanation: Place the two introverts in (1,1) and (3,1) and the extrovert at (2,1). - Introvert at (1,1) happiness: 120 (starting happiness) - (1 * 30) (1 neighbor) = 90 - Extrovert at (2,1) happiness: 40 (starting happiness) + (2 * 20) (2 neighbors) = 80 - Introvert at (3,1) happiness: 120 (starting happiness) - (1 * 30) (1 neighbor) = 90 The grid happiness is 90 + 80 + 90 = 260. Example 3: Input: m = 2, n = 2, introvertsCount = 4, extrovertsCount = 0 Output: 240 Constraints: 1 <= m, n <= 5 0 <= introvertsCount, extrovertsCount <= min(m * n, 6)
[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 string "ab" + "c" -> "abc" word2 represents string "a" + "bc" -> "abc" The strings are the same, so return true. Example 2: Input: word1 = ["a", "cb"], word2 = ["ab", "c"] Output: false Example 3: Input: word1 = ["abc", "d", "defg"], word2 = ["abcddefg"] Output: true Constraints: 1 <= word1.length, word2.length <= 103 1 <= word1[i].length, word2[i].length <= 103 1 <= sum(word1[i].length), sum(word2[i].length) <= 103 word1[i] and word2[i] consist of lowercase letters.
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. For example, the numeric value of the string "abe" is equal to 1 + 2 + 5 = 8. You are given two integers n and k. Return the lexicographically smallest string with length equal to n and numeric value equal to k. Note that a string x is lexicographically smaller than string y if x comes before y in dictionary order, that is, either x is a prefix of y, or if i is the first position such that x[i] != y[i], then x[i] comes before y[i] in alphabetic order. Example 1: Input: n = 3, k = 27 Output: "aay" Explanation: The numeric value of the string is 1 + 1 + 25 = 27, and it is the smallest string with such a value and length equal to 3. Example 2: Input: n = 5, k = 73 Output: "aaszz" Constraints: 1 <= n <= 105 n <= k <= 26 * n
✔️ [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 == 1: prefixOdd, prefixEven = prefixEven, prefixOdd if i > 1: if i % 2 == 0: prefixEven -= nums[i-1] prefixEven += nums[i-2] else: prefixOdd -= nums[i-1] prefixOdd += nums[i-2] if prefixOdd == prefixEven: result += 1 return result
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]. Choosing to remove index 4 results in nums = [6,1,7,4]. An array is fair if the sum of the odd-indexed values equals the sum of the even-indexed values. Return the number of indices that you could choose such that after the removal, nums is fair. Example 1: Input: nums = [2,1,6,4] Output: 1 Explanation: Remove index 0: [1,6,4] -> Even sum: 1 + 4 = 5. Odd sum: 6. Not fair. Remove index 1: [2,6,4] -> Even sum: 2 + 4 = 6. Odd sum: 6. Fair. Remove index 2: [2,1,4] -> Even sum: 2 + 4 = 6. Odd sum: 1. Not fair. Remove index 3: [2,1,6] -> Even sum: 2 + 6 = 8. Odd sum: 1. Not fair. There is 1 index that you can remove to make nums fair. Example 2: Input: nums = [1,1,1] Output: 3 Explanation: You can remove any index and the remaining array is fair. Example 3: Input: nums = [1,2,3] Output: 0 Explanation: You cannot make a fair array after removing any index. Constraints: 1 <= nums.length <= 105 1 <= nums[i] <= 104
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 l, r = 0, 10 ** 9 while l <= r: mid = (l+r) // 2 if ok(mid): r = mid - 1 else: l = mid + 1 return l
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, if your current energy is 13, you can complete this task, and your energy will be 3 after finishing it. You can finish the tasks in any order you like. Return the minimum initial amount of energy you will need to finish all the tasks. Example 1: Input: tasks = [[1,2],[2,4],[4,8]] Output: 8 Explanation: Starting with 8 energy, we finish the tasks in the following order: - 3rd task. Now energy = 8 - 4 = 4. - 2nd task. Now energy = 4 - 2 = 2. - 1st task. Now energy = 2 - 1 = 1. Notice that even though we have leftover energy, starting with 7 energy does not work because we cannot do the 3rd task. Example 2: Input: tasks = [[1,3],[2,4],[10,11],[10,12],[8,9]] Output: 32 Explanation: Starting with 32 energy, we finish the tasks in the following order: - 1st task. Now energy = 32 - 1 = 31. - 2nd task. Now energy = 31 - 2 = 29. - 3rd task. Now energy = 29 - 10 = 19. - 4th task. Now energy = 19 - 10 = 9. - 5th task. Now energy = 9 - 8 = 1. Example 3: Input: tasks = [[1,7],[2,8],[3,9],[4,10],[5,11],[6,12]] Output: 27 Explanation: Starting with 27 energy, we finish the tasks in the following order: - 5th task. Now energy = 27 - 5 = 22. - 2nd task. Now energy = 22 - 2 = 20. - 3rd task. Now energy = 20 - 3 = 17. - 1st task. Now energy = 17 - 1 = 16. - 4th task. Now energy = 16 - 4 = 12. - 6th task. Now energy = 12 - 6 = 6. Constraints: 1 <= tasks.length <= 105 1 <= actuali <= minimumi <= 104
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, return the maximum k-repeating value of word in sequence. Example 1: Input: sequence = "ababc", word = "ab" Output: 2 Explanation: "abab" is a substring in "ababc". Example 2: Input: sequence = "ababc", word = "ba" Output: 1 Explanation: "ba" is a substring in "ababc". "baba" is not a substring in "ababc". Example 3: Input: sequence = "ababc", word = "ac" Output: 0 Explanation: "ac" is not a substring in "ababc". Constraints: 1 <= sequence.length <= 100 1 <= word.length <= 100 sequence and word contains only lowercase English letters.
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 # continue travel to b node --> step 2 start.next=list2 # point start to list2 --> step3 while list2.next: # travel list2 --> step 4 list2=list2.next list2.next=curr.next # map end of list2 to b return list1
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], a = 3, b = 4, list2 = [1000000,1000001,1000002] Output: [10,1,13,1000000,1000001,1000002,5] Explanation: We remove the nodes 3 and 4 and put the entire list2 in their place. The blue edges and nodes in the above figure indicate the result. Example 2: Input: list1 = [0,1,2,3,4,5,6], a = 2, b = 5, list2 = [1000000,1000001,1000002,1000003,1000004] Output: [0,1,1000000,1000001,1000002,1000003,1000004,6] Explanation: The blue edges and nodes in the above figure indicate the result. Constraints: 3 <= list1.length <= 104 1 <= a <= b < list1.length - 1 1 <= list2.length <= 104
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, -1, -1): # for decreasing subsequence maxi1 = 0 for j in range(l - 1, i, -1): if lst[i] > lst[j]: if dp1[j] > maxi1: maxi1 = dp1[j] dp1[i] = maxi1 + 1 ans = 0 for i in range(l): if dp[i] > 1 and dp1[i] > 1: temp = dp[i] + dp1[i] - 1 if temp > ans: ans = temp return l - ans
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 to remove to make nums a mountain array. Example 1: Input: nums = [1,3,1] Output: 0 Explanation: The array itself is a mountain array so we do not need to remove any elements. Example 2: Input: nums = [2,1,1,5,6,2,3,1] Output: 3 Explanation: One solution is to remove the elements at indices 0, 1, and 5, making the array nums = [1,5,6,3,1]. Constraints: 3 <= nums.length <= 1000 1 <= nums[i] <= 109 It is guaranteed that you can make a mountain array out of nums.
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 wealth. Example 1: Input: accounts = [[1,2,3],[3,2,1]] Output: 6 Explanation: 1st customer has wealth = 1 + 2 + 3 = 6 2nd customer has wealth = 3 + 2 + 1 = 6 Both customers are considered the richest with a wealth of 6 each, so return 6. Example 2: Input: accounts = [[1,5],[7,3],[3,5]] Output: 10 Explanation: 1st customer has wealth = 6 2nd customer has wealth = 10 3rd customer has wealth = 8 The 2nd customer is the richest with a wealth of 10. Example 3: Input: accounts = [[2,8,7],[7,1,3],[1,9,5]] Output: 17 Constraints: m == accounts.length n == accounts[i].length 1 <= m, n <= 50 1 <= accounts[i][j] <= 100
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 stack
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) if in the first position where a and b differ, subsequence a has a number less than the corresponding number in b. For example, [1,3,4] is more competitive than [1,3,5] because the first position they differ is at the final number, and 4 is less than 5. Example 1: Input: nums = [3,5,2,6], k = 2 Output: [2,6] Explanation: Among the set of every possible subsequence: {[3,5], [3,2], [3,6], [5,2], [5,6], [2,6]}, [2,6] is the most competitive. Example 2: Input: nums = [2,4,3,3,5,4,9,6], k = 4 Output: [2,3,3,4] Constraints: 1 <= nums.length <= 105 0 <= nums[i] <= 109 1 <= k <= nums.length
[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], nums[n-1-i]) + limit overlay_arr[left_boundary] -= 1 overlay_arr[no_move_value] -= 1 overlay_arr[no_move_value+1] += 1 overlay_arr[right_boundary+1] += 1 curr_moves = n #initial assumption of two moves for each pair res = float("inf") # start Sweeping for i in range(2, 2*limit+1): curr_moves += overlay_arr[i] res = min(res, curr_moves) return res
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,2,3,4] is complementary because for all indices i, nums[i] + nums[n - 1 - i] = 5. Return the minimum number of moves required to make nums complementary. Example 1: Input: nums = [1,2,4,3], limit = 4 Output: 1 Explanation: In 1 move, you can change nums to [1,2,2,3] (underlined elements are changed). nums[0] + nums[3] = 1 + 3 = 4. nums[1] + nums[2] = 2 + 2 = 4. nums[2] + nums[1] = 2 + 2 = 4. nums[3] + nums[0] = 3 + 1 = 4. Therefore, nums[i] + nums[n-1-i] = 4 for every i, so nums is complementary. Example 2: Input: nums = [1,2,2,1], limit = 2 Output: 2 Explanation: In 2 moves, you can change nums to [2,2,2,2]. You cannot change any number to 3 since 3 > limit. Example 3: Input: nums = [1,2,1,2], limit = 2 Output: 0 Explanation: nums is already complementary. Constraints: n == nums.length 2 <= n <= 105 1 <= nums[i] <= limit <= 105 n is even.
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 == 0: nums.pop() nums.add(max_value // 2) max_value = nums[-1] min_value = nums[0] result = min(result , max_value - min_value) else: result = min(result , max_value - min_value) break return result
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 is odd, multiply it by 2. For example, if the array is [1,2,3,4], then you can do this operation on the first element, and the array will be [2,2,3,4]. The deviation of the array is the maximum difference between any two elements in the array. Return the minimum deviation the array can have after performing some number of operations. Example 1: Input: nums = [1,2,3,4] Output: 1 Explanation: You can transform the array to [1,2,3,2], then to [2,2,3,2], then the deviation will be 3 - 2 = 1. Example 2: Input: nums = [4,1,5,20,3] Output: 3 Explanation: You can transform the array after two operations to [4,2,5,5,3], then the deviation will be 5 - 2 = 3. Example 3: Input: nums = [2,10,8] Output: 3 Constraints: n == nums.length 2 <= n <= 5 * 104 1 <= nums[i] <= 109
[ 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 the string command, return the Goal Parser's interpretation of command. Example 1: Input: command = "G()(al)" Output: "Goal" Explanation: The Goal Parser interprets the command as follows: G -> G () -> o (al) -> al The final concatenated result is "Goal". Example 2: Input: command = "G()()()()(al)" Output: "Gooooal" Example 3: Input: command = "(al)G(al)()()G" Output: "alGalooG" Constraints: 1 <= command.length <= 100 command consists of "G", "()", and/or "(al)" in some order.
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] +=1 return count
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 = [1,2,3,4]: - Remove numbers 1 and 4, then nums = [2,3] - Remove numbers 2 and 3, then nums = [] There are no more pairs that sum up to 5, hence a total of 2 operations. Example 2: Input: nums = [3,1,3,4,3], k = 6 Output: 1 Explanation: Starting with nums = [3,1,3,4,3]: - Remove the first two 3's, then nums = [1,4,3] There are no more pairs that sum up to 6, hence a total of 1 operation. Constraints: 1 <= nums.length <= 105 1 <= nums[i] <= 109 1 <= k <= 109
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, and 3 corresponds to "1", "10", and "11". After concatenating them, we have "11011", which corresponds to the decimal value 27. Example 3: Input: n = 12 Output: 505379714 Explanation: The concatenation results in "1101110010111011110001001101010111100". The decimal value of that is 118505380540. After modulo 109 + 7, the result is 505379714. Constraints: 1 <= n <= 105
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 if i == len(nums): ans = cand else: for ii in range(k): if len(stack[ii]) < len(nums)//k and (not stack[ii] or stack[ii][-1] != nums[i]) and (not ii or stack[ii-1] != stack[ii]): stack[ii].append(nums[i]) if len(stack[ii]) == 1: fn(i+1, cand) else: fn(i+1, cand + stack[ii][-1] - stack[ii][-2]) stack[ii].pop() ans = inf stack = [[] for _ in range(k)] fn(0, 0) return ans if ans < inf else -1
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 incompatibilities of the k subsets after distributing the array optimally, or return -1 if it is not possible. A subset is a group integers that appear in the array with no particular order. Example 1: Input: nums = [1,2,1,4], k = 2 Output: 4 Explanation: The optimal distribution of subsets is [1,2] and [1,4]. The incompatibility is (2-1) + (4-1) = 4. Note that [1,1] and [2,4] would result in a smaller sum, but the first subset contains 2 equal elements. Example 2: Input: nums = [6,3,8,1,3,1,2,2], k = 4 Output: 6 Explanation: The optimal distribution of subsets is [1,2], [2,3], [6,8], and [1,3]. The incompatibility is (2-1) + (3-2) + (8-6) + (3-1) = 6. Example 3: Input: nums = [5,3,3,6,3,3], k = 3 Output: -1 Explanation: It is impossible to distribute nums into 3 subsets where no two elements are equal in the same subset. Constraints: 1 <= k <= nums.length <= 16 nums.length is divisible by k 1 <= nums[i] <= nums.length
[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"] Output: 2 Explanation: Strings "aaab" and "baa" are consistent since they only contain characters 'a' and 'b'. Example 2: Input: allowed = "abc", words = ["a","b","c","ab","ac","bc","abc"] Output: 7 Explanation: All strings are consistent. Example 3: Input: allowed = "cad", words = ["cc","acd","b","ba","bac","bad","ac","d"] Output: 4 Explanation: Strings "cc", "acd", "ac", and "d" are consistent. Constraints: 1 <= words.length <= 104 1 <= allowed.length <= 26 1 <= words[i].length <= 10 The characters in allowed are distinct. words[i] and allowed contain only lowercase English letters.
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 return [(num*(i+1) - pre_sum[i+1]) + (pre_sum[-1]-pre_sum[i] - (n-i)*num) for i, num in enumerate(nums)]
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[j]|) where 0 <= j < nums.length and j != i (0-indexed). Example 1: Input: nums = [2,3,5] Output: [4,3,5] Explanation: Assuming the arrays are 0-indexed, then result[0] = |2-2| + |2-3| + |2-5| = 0 + 1 + 3 = 4, result[1] = |3-2| + |3-3| + |3-5| = 1 + 0 + 2 = 3, result[2] = |5-2| + |5-3| + |5-5| = 3 + 2 + 0 = 5. Example 2: Input: nums = [1,4,6,8,10] Output: [24,15,13,15,21] Constraints: 2 <= nums.length <= 105 1 <= nums[i] <= nums[i + 1] <= 104
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] if res > s: return 1 elif res == s: return 0 else: return -1
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 bobValues. Each aliceValues[i] and bobValues[i] represents how Alice and Bob, respectively, value the ith stone. The winner is the person with the most points after all the stones are chosen. If both players have the same amount of points, the game results in a draw. Both players will play optimally. Both players know the other's values. Determine the result of the game, and: If Alice wins, return 1. If Bob wins, return -1. If the game results in a draw, return 0. Example 1: Input: aliceValues = [1,3], bobValues = [2,1] Output: 1 Explanation: If Alice takes stone 1 (0-indexed) first, Alice will receive 3 points. Bob can only choose stone 0, and will only receive 2 points. Alice wins. Example 2: Input: aliceValues = [1,2], bobValues = [3,1] Output: 0 Explanation: If Alice takes stone 0, and Bob takes stone 1, they will both have 1 point. Draw. Example 3: Input: aliceValues = [2,4,3], bobValues = [1,6,7] Output: -1 Explanation: Regardless of how Alice plays, Bob will be able to have more points than Alice. For example, if Alice takes stone 1, Bob can take stone 2, and Alice takes stone 0, Alice will have 6 points to Bob's 7. Bob wins. Constraints: n == aliceValues.length == bobValues.length 1 <= n <= 105 1 <= aliceValues[i], bobValues[i] <= 100
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]: trips += 1 while maxBoxes < i - ii + 1 or maxWeight < 0 or ii < i and dp[ii] == dp[ii+1]: maxWeight += boxes[ii][1] if boxes[ii][0] != boxes[ii+1][0]: trips-=1 ii += 1 dp[i+1] = dp[ii] + trips return dp[-1]
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 the port where you need to deliver the ith box and weightsi is the weight of the ith box. portsCount is the number of ports. maxBoxes and maxWeight are the respective box and weight limits of the ship. The boxes need to be delivered in the order they are given. The ship will follow these steps: The ship will take some number of boxes from the boxes queue, not violating the maxBoxes and maxWeight constraints. For each loaded box in order, the ship will make a trip to the port the box needs to be delivered to and deliver it. If the ship is already at the correct port, no trip is needed, and the box can immediately be delivered. The ship then makes a return trip to storage to take more boxes from the queue. The ship must end at storage after all the boxes have been delivered. Return the minimum number of trips the ship needs to make to deliver all boxes to their respective ports. Example 1: Input: boxes = [[1,1],[2,1],[1,1]], portsCount = 2, maxBoxes = 3, maxWeight = 3 Output: 4 Explanation: The optimal strategy is as follows: - The ship takes all the boxes in the queue, goes to port 1, then port 2, then port 1 again, then returns to storage. 4 trips. So the total number of trips is 4. Note that the first and third boxes cannot be delivered together because the boxes need to be delivered in order (i.e. the second box needs to be delivered at port 2 before the third box). Example 2: Input: boxes = [[1,2],[3,3],[3,1],[3,1],[2,4]], portsCount = 3, maxBoxes = 3, maxWeight = 6 Output: 6 Explanation: The optimal strategy is as follows: - The ship takes the first box, goes to port 1, then returns to storage. 2 trips. - The ship takes the second, third and fourth boxes, goes to port 3, then returns to storage. 2 trips. - The ship takes the fifth box, goes to port 2, then returns to storage. 2 trips. So the total number of trips is 2 + 2 + 2 = 6. Example 3: Input: boxes = [[1,4],[1,2],[2,1],[2,1],[3,2],[3,4]], portsCount = 3, maxBoxes = 6, maxWeight = 7 Output: 6 Explanation: The optimal strategy is as follows: - The ship takes the first and second boxes, goes to port 1, then returns to storage. 2 trips. - The ship takes the third and fourth boxes, goes to port 2, then returns to storage. 2 trips. - The ship takes the fifth and sixth boxes, goes to port 3, then returns to storage. 2 trips. So the total number of trips is 2 + 2 + 2 = 6. Constraints: 1 <= boxes.length <= 105 1 <= portsCount, maxBoxes, maxWeight <= 105 1 <= portsi <= portsCount 1 <= weightsi <= maxWeight
[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 the tournament, and the rest gets paired. A total of (n - 1) / 2 matches are played, and (n - 1) / 2 + 1 teams advance to the next round. Return the number of matches played in the tournament until a winner is decided. Example 1: Input: n = 7 Output: 6 Explanation: Details of the tournament: - 1st Round: Teams = 7, Matches = 3, and 4 teams advance. - 2nd Round: Teams = 4, Matches = 2, and 2 teams advance. - 3rd Round: Teams = 2, Matches = 1, and 1 team is declared the winner. Total number of matches = 3 + 2 + 1 = 6. Example 2: Input: n = 14 Output: 13 Explanation: Details of the tournament: - 1st Round: Teams = 14, Matches = 7, and 7 teams advance. - 2nd Round: Teams = 7, Matches = 3, and 4 teams advance. - 3rd Round: Teams = 4, Matches = 2, and 2 teams advance. - 4th Round: Teams = 2, Matches = 1, and 1 team is declared the winner. Total number of matches = 7 + 3 + 2 + 1 = 13. Constraints: 1 <= n <= 200
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 up to n. Example 1: Input: n = "32" Output: 3 Explanation: 10 + 11 + 11 = 32 Example 2: Input: n = "82734" Output: 8 Example 3: Input: n = "27346209830709182346" Output: 9 Constraints: 1 <= n.length <= 105 n consists of only digits. n does not contain any leading zeros and represents a positive integer.
[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 sum for i in stones: s += i run_sum.append(s) n = len(stones) for k in range(1, n): # no. of stones left for i in range(0, n - k): # from each starting point remove_i_stone = (run_sum[i+k+1] - run_sum[i+1]) # score after removing i th stone remove_j_stone = (run_sum[i+k] - run_sum[i]) # score after removing j th stone if (n-(k+1))%2 == 0: # alice's move dp[i][i+k] = max(remove_i_stone + dp[i+1][i+k], remove_j_stone + dp[i][i+k-1]) else: # bob's move dp[i][i+k] = min(-remove_i_stone + dp[i+1][i+k], - remove_j_stone + dp[i][i+k-1]) return dp[0][n - 1]
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 higher score when there are no stones left to remove. Bob found that he will always lose this game (poor Bob, he always loses), so he decided to minimize the score's difference. Alice's goal is to maximize the difference in the score. Given an array of integers stones where stones[i] represents the value of the ith stone from the left, return the difference in Alice and Bob's score if they both play optimally. Example 1: Input: stones = [5,3,1,4,2] Output: 6 Explanation: - Alice removes 2 and gets 5 + 3 + 1 + 4 = 13 points. Alice = 13, Bob = 0, stones = [5,3,1,4]. - Bob removes 5 and gets 3 + 1 + 4 = 8 points. Alice = 13, Bob = 8, stones = [3,1,4]. - Alice removes 3 and gets 1 + 4 = 5 points. Alice = 18, Bob = 8, stones = [1,4]. - Bob removes 1 and gets 4 points. Alice = 18, Bob = 12, stones = [4]. - Alice removes 4 and gets 0 points. Alice = 18, Bob = 12, stones = []. The score difference is 18 - 12 = 6. Example 2: Input: stones = [7,90,5,1,100,10,10,2] Output: 122 Constraints: n == stones.length 2 <= n <= 1000 1 <= stones[i] <= 1000
[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 be put on top of x n = len(cuboids) dp = [cu[2] for cu in cuboids] # create dp array ans = max(dp) for i in range(1, n): # iterate over each cube for j in range(i): # compare with previous calculated cube if ok(cuboids[j], cuboids[i]): # update dp[i] if cube[i] can be put on top of cube[j] dp[i] = max(dp[i], dp[j] + cuboids[i][2]) # always get the maximum ans = max(ans, dp[i]) # record the largest value return ans
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 rotating it to put it on another cuboid. Return the maximum height of the stacked cuboids. Example 1: Input: cuboids = [[50,45,20],[95,37,53],[45,23,12]] Output: 190 Explanation: Cuboid 1 is placed on the bottom with the 53x37 side facing down with height 95. Cuboid 0 is placed next with the 45x20 side facing down with height 50. Cuboid 2 is placed next with the 23x12 side facing down with height 45. The total height is 95 + 50 + 45 = 190. Example 2: Input: cuboids = [[38,25,45],[76,35,3]] Output: 76 Explanation: You can't place any of the cuboids on the other. We choose cuboid 1 and rotate it so that the 35x3 side is facing down and its height is 76. Example 3: Input: cuboids = [[7,11,17],[7,17,11],[11,7,17],[11,17,7],[17,7,11],[17,11,7]] Output: 102 Explanation: After rearranging the cuboids, you can see that all cuboids have the same dimension. You can place the 11x7 side down on all cuboids so their heights are 17. The maximum height of stacked cuboids is 6 * 17 = 102. Constraints: n == cuboids.length 1 <= n <= 100 1 <= widthi, lengthi, heighti <= 100
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([number[i:i+2], number[i+2:]]) break return "-".join(ans)
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 final digits are then grouped as follows: 2 digits: A single block of length 2. 3 digits: A single block of length 3. 4 digits: Two blocks of length 2 each. The blocks are then joined by dashes. Notice that the reformatting process should never produce any blocks of length 1 and produce at most two blocks of length 2. Return the phone number after formatting. Example 1: Input: number = "1-23-45 6" Output: "123-456" Explanation: The digits are "123456". Step 1: There are more than 4 digits, so group the next 3 digits. The 1st block is "123". Step 2: There are 3 digits remaining, so put them in a single block of length 3. The 2nd block is "456". Joining the blocks gives "123-456". Example 2: Input: number = "123 4-567" Output: "123-45-67" Explanation: The digits are "1234567". Step 1: There are more than 4 digits, so group the next 3 digits. The 1st block is "123". Step 2: There are 4 digits left, so split them into two blocks of length 2. The blocks are "45" and "67". Joining the blocks gives "123-45-67". Example 3: Input: number = "123 4-5678" Output: "123-456-78" Explanation: The digits are "12345678". Step 1: The 1st block is "123". Step 2: The 2nd block is "456". Step 3: There are 2 digits left, so put them in a single block of length 2. The 3rd block is "78". Joining the blocks gives "123-456-78". Constraints: 2 <= number.length <= 100 number consists of digits and the characters '-' and ' '. There are at least two digits in number.
[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 sliding window until you get all unique elements while i < j and counter[x]>1: counter[nums[i]]-=1 tot-=nums[i] i+=1 res=max(res, tot) return res
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 contiguous subsequence of a, that is, if it is equal to a[l],a[l+1],...,a[r] for some (l,r). Example 1: Input: nums = [4,2,4,5,6] Output: 17 Explanation: The optimal subarray here is [2,4,5,6]. Example 2: Input: nums = [5,2,1,2,5,2,1,2,5] Output: 8 Explanation: The optimal subarray here is [5,2,1] or [1,2,5]. Constraints: 1 <= nums.length <= 105 1 <= nums[i] <= 104
✅ 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 the last index of the array (index n - 1). Your score is the sum of all nums[j] for each index j you visited in the array. Return the maximum score you can get. Example 1: Input: nums = [1,-1,-2,4,-7,3], k = 2 Output: 7 Explanation: You can choose your jumps forming the subsequence [1,-1,4,3] (underlined above). The sum is 7. Example 2: Input: nums = [10,-5,-2,4,0,3], k = 3 Output: 17 Explanation: You can choose your jumps forming the subsequence [10,4,3] (underlined above). The sum is 17. Example 3: Input: nums = [1,-5,-20,4,-1,3,-6,-3], k = 2 Output: 0 Constraints: 1 <= nums.length, k <= 105 -104 <= nums[i] <= 104
[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 parent[x] = find(parent, parent[x]) return parent[x] def union(parent, a, b): a = find(parent, a) b = find(parent, b) if a == b: return if rank[a] < rank[b]: parent[a] = b elif rank[a] > rank[b]: parent[b] = a else: parent[b] = a rank[a] += 1 edgeList.sort(key = lambda x: x[2]) res = [0] * len(queries) queries = [[i, ch] for i, ch in enumerate(queries)] queries.sort(key = lambda x: x[1][2]) ind = 0 for i, (a, b, w) in queries: while ind < len(edgeList) and edgeList[ind][2] < w: union(parent, edgeList[ind][0], edgeList[ind][1]) ind += 1 res[i] = find(parent, a) == find(parent, b) return res
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] whether there is a path between pj and qj such that each edge on the path has a distance strictly less than limitj . Return a boolean array answer, where answer.length == queries.length and the jth value of answer is true if there is a path for queries[j] is true, and false otherwise. Example 1: Input: n = 3, edgeList = [[0,1,2],[1,2,4],[2,0,8],[1,0,16]], queries = [[0,1,2],[0,2,5]] Output: [false,true] Explanation: The above figure shows the given graph. Note that there are two overlapping edges between 0 and 1 with distances 2 and 16. For the first query, between 0 and 1 there is no path where each distance is less than 2, thus we return false for this query. For the second query, there is a path (0 -> 1 -> 2) of two edges with distances less than 5, thus we return true for this query. Example 2: Input: n = 5, edgeList = [[0,1,10],[1,2,5],[2,3,9],[3,4,13]], queries = [[0,4,14],[1,4,13]] Output: [true,false] Explanation: The above figure shows the given graph. Constraints: 2 <= n <= 105 1 <= edgeList.length, queries.length <= 105 edgeList[i].length == 3 queries[j].length == 3 0 <= ui, vi, pj, qj <= n - 1 ui != vi pj != qj 1 <= disi, limitj <= 109 There may be multiple edges between two nodes.
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: curr += 1 students.append(students.pop(0)) if(curr >= len(students)): break return len(students)
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 stack. At each step: If the student at the front of the queue prefers the sandwich on the top of the stack, they will take it and leave the queue. Otherwise, they will leave it and go to the queue's end. This continues until none of the queue students want to take the top sandwich and are thus unable to eat. You are given two integer arrays students and sandwiches where sandwiches[i] is the type of the ith sandwich in the stack (i = 0 is the top of the stack) and students[j] is the preference of the jth student in the initial queue (j = 0 is the front of the queue). Return the number of students that are unable to eat. Example 1: Input: students = [1,1,0,0], sandwiches = [0,1,0,1] Output: 0 Explanation: - Front student leaves the top sandwich and returns to the end of the line making students = [1,0,0,1]. - Front student leaves the top sandwich and returns to the end of the line making students = [0,0,1,1]. - Front student takes the top sandwich and leaves the line making students = [0,1,1] and sandwiches = [1,0,1]. - Front student leaves the top sandwich and returns to the end of the line making students = [1,1,0]. - Front student takes the top sandwich and leaves the line making students = [1,0] and sandwiches = [0,1]. - Front student leaves the top sandwich and returns to the end of the line making students = [0,1]. - Front student takes the top sandwich and leaves the line making students = [1] and sandwiches = [1]. - Front student takes the top sandwich and leaves the line making students = [] and sandwiches = []. Hence all students are able to eat. Example 2: Input: students = [1,1,1,0,0,1], sandwiches = [1,0,0,0,1,1] Output: 3 Constraints: 1 <= students.length, sandwiches.length <= 100 students.length == sandwiches.length sandwiches[i] is 0 or 1. students[i] is 0 or 1.
[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) return sum(arr) / len(arr)
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 the chef his order, and the chef starts preparing it once he is idle. The customer waits till the chef finishes preparing his order. The chef does not prepare food for more than one customer at a time. The chef prepares food for customers in the order they were given in the input. Return the average waiting time of all customers. Solutions within 10-5 from the actual answer are considered accepted. Example 1: Input: customers = [[1,2],[2,5],[4,3]] Output: 5.00000 Explanation: 1) The first customer arrives at time 1, the chef takes his order and starts preparing it immediately at time 1, and finishes at time 3, so the waiting time of the first customer is 3 - 1 = 2. 2) The second customer arrives at time 2, the chef takes his order and starts preparing it at time 3, and finishes at time 8, so the waiting time of the second customer is 8 - 2 = 6. 3) The third customer arrives at time 4, the chef takes his order and starts preparing it at time 8, and finishes at time 11, so the waiting time of the third customer is 11 - 4 = 7. So the average waiting time = (2 + 6 + 7) / 3 = 5. Example 2: Input: customers = [[5,2],[5,4],[10,3],[20,1]] Output: 3.25000 Explanation: 1) The first customer arrives at time 5, the chef takes his order and starts preparing it immediately at time 5, and finishes at time 7, so the waiting time of the first customer is 7 - 5 = 2. 2) The second customer arrives at time 5, the chef takes his order and starts preparing it at time 7, and finishes at time 11, so the waiting time of the second customer is 11 - 5 = 6. 3) The third customer arrives at time 10, the chef takes his order and starts preparing it at time 11, and finishes at time 14, so the waiting time of the third customer is 14 - 10 = 4. 4) The fourth customer arrives at time 20, the chef takes his order and starts preparing it immediately at time 20, and finishes at time 21, so the waiting time of the fourth customer is 21 - 20 = 1. So the average waiting time = (2 + 6 + 4 + 1) / 4 = 3.25. Constraints: 1 <= customers.length <= 105 1 <= arrivali, timei <= 104 arrivali <= arrivali+1
[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": c+=1 for i in range (0,len(s)): #finding the ist 0 if s[i]=="0": lst[i+c-1]="0" return "".join(lst) return s
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 replace it with "01". For example, "00010" -> "00001" Return the maximum binary string you can obtain after any number of operations. Binary string x is greater than binary string y if x's decimal representation is greater than y's decimal representation. Example 1: Input: binary = "000110" Output: "111011" Explanation: A valid transformation sequence can be: "000110" -> "000101" "000101" -> "100101" "100101" -> "110101" "110101" -> "110011" "110011" -> "111011" Example 2: Input: binary = "01" Output: "01" Explanation: "01" cannot be transformed any further. Constraints: 1 <= binary.length <= 105 binary consist of '0' and '1'.
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] - loc[m] - (len(loc)-ii)//2 # adding right if len(loc) - ii > k: m = (ii + len(loc))//2 # updated median val -= loc[m] - loc[ii] - (len(loc)-ii)//2 # removing left ii += 1 if len(loc)-ii == k: ans = min(ans, val) # len(ones) - ii effective length return ans
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 move, nums could be [1,0,0,0,1,1] and have 2 consecutive 1's. Example 2: Input: nums = [1,0,0,0,0,0,1,1], k = 3 Output: 5 Explanation: In 5 moves, the leftmost 1 can be shifted right until nums = [0,0,0,0,0,1,1,1]. Example 3: Input: nums = [1,1,0,1], k = 2 Output: 0 Explanation: nums already has 2 consecutive 1's. Constraints: 1 <= nums.length <= 105 nums[i] is 0 or 1. 1 <= k <= sum(nums)
[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. Return true if a and b are alike. Otherwise, return false. Example 1: Input: s = "book" Output: true Explanation: a = "bo" and b = "ok". a has 1 vowel and b has 1 vowel. Therefore, they are alike. Example 2: Input: s = "textbook" Output: false Explanation: a = "text" and b = "book". a has 1 vowel whereas b has 2. Therefore, they are not alike. Notice that the vowel o is counted twice. Constraints: 2 <= s.length <= 1000 s.length is even. s consists of uppercase and lowercase letters.
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: ii, x = heappop(pq) if x-1: heappush(pq, (ii, x-1)) ans += 1 i += 1 while pq: ii, x = heappop(pq) x = min(x, ii-i) ans += x i += x return ans
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] == 0 and days[i] == 0. You decided to eat at most one apple a day (to keep the doctors away). Note that you can keep eating after the first n days. Given two integer arrays days and apples of length n, return the maximum number of apples you can eat. Example 1: Input: apples = [1,2,3,5,2], days = [3,2,1,4,2] Output: 7 Explanation: You can eat 7 apples: - On the first day, you eat an apple that grew on the first day. - On the second day, you eat an apple that grew on the second day. - On the third day, you eat an apple that grew on the second day. After this day, the apples that grew on the third day rot. - On the fourth to the seventh days, you eat apples that grew on the fourth day. Example 2: Input: apples = [3,0,0,0,0,2], days = [3,0,0,0,0,2] Output: 5 Explanation: You can eat 5 apples: - On the first to the third day you eat apples that grew on the first day. - Do nothing on the fouth and fifth days. - On the sixth and seventh days you eat apples that grew on the sixth day. Constraints: n == apples.length == days.length 1 <= n <= 2 * 104 0 <= apples[i], days[i] <= 2 * 104 days[i] = 0 if and only if apples[i] = 0.
[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) elif grid[r][c] == -1 and 0 <= c-1 and grid[r][c-1] == -1: return helper(r+1, c-1) else: return -1 return [helper(0, j) for j in range(n)]
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 to the bottom-right corner and is represented in the grid as 1. A board that redirects the ball to the left spans the top-right corner to the bottom-left corner and is represented in the grid as -1. We drop one ball at the top of each column of the box. Each ball can get stuck in the box or fall out of the bottom. A ball gets stuck if it hits a "V" shaped pattern between two boards or if a board redirects the ball into either wall of the box. Return an array answer of size n where answer[i] is the column that the ball falls out of at the bottom after dropping the ball from the ith column at the top, or -1 if the ball gets stuck in the box. Example 1: Input: grid = [[1,1,1,-1,-1],[1,1,1,-1,-1],[-1,-1,-1,1,1],[1,1,1,1,-1],[-1,-1,-1,-1,-1]] Output: [1,-1,-1,-1,-1] Explanation: This example is shown in the photo. Ball b0 is dropped at column 0 and falls out of the box at column 1. Ball b1 is dropped at column 1 and will get stuck in the box between column 2 and 3 and row 1. Ball b2 is dropped at column 2 and will get stuck on the box between column 2 and 3 and row 0. Ball b3 is dropped at column 3 and will get stuck on the box between column 2 and 3 and row 0. Ball b4 is dropped at column 4 and will get stuck on the box between column 2 and 3 and row 1. Example 2: Input: grid = [[-1]] Output: [-1] Explanation: The ball gets stuck against the left wall. Example 3: Input: grid = [[1,1,1,1,1,1],[-1,-1,-1,-1,-1,-1],[1,1,1,1,1,1],[-1,-1,-1,-1,-1,-1]] Output: [0,1,2,3,4,-1] Constraints: m == grid.length n == grid[i].length 1 <= m, n <= 100 grid[i][j] is 1 or -1.
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 < len(nums) and nums[k] <= m: node = trie val = bin(nums[k])[2:].zfill(32) for c in val: node = node.setdefault(int(c), {}) node["#"] = nums[k] k += 1 if trie: node = trie val = bin(x)[2:].zfill(32) for c in val: node = node.get(1-int(c)) or node.get(int(c)) ans[i] = x ^ node["#"] return ans
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[j] <= mi. If all elements in nums are larger than mi, then the answer is -1. Return an integer array answer where answer.length == queries.length and answer[i] is the answer to the ith query. Example 1: Input: nums = [0,1,2,3,4], queries = [[3,1],[1,3],[5,6]] Output: [3,3,7] Explanation: 1) 0 and 1 are the only two integers not greater than 1. 0 XOR 3 = 3 and 1 XOR 3 = 2. The larger of the two is 3. 2) 1 XOR 2 = 3. 3) 5 XOR 2 = 7. Example 2: Input: nums = [5,2,4,6,6,3], queries = [[12,4],[8,1],[6,3]] Output: [15,-1,5] Constraints: 1 <= nums.length, queries.length <= 105 queries[i].length == 2 0 <= nums[j], xi, mi <= 109
[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 return s
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, which is the maximum number of boxes that can be put on the truck. You can choose any boxes to put on the truck as long as the number of boxes does not exceed truckSize. Return the maximum total number of units that can be put on the truck. Example 1: Input: boxTypes = [[1,3],[2,2],[3,1]], truckSize = 4 Output: 8 Explanation: There are: - 1 box of the first type that contains 3 units. - 2 boxes of the second type that contain 2 units each. - 3 boxes of the third type that contain 1 unit each. You can take all the boxes of the first and second types, and one box of the third type. The total number of units will be = (1 * 3) + (2 * 2) + (1 * 1) = 8. Example 2: Input: boxTypes = [[5,10],[2,5],[4,7],[3,9]], truckSize = 10 Output: 91 Constraints: 1 <= boxTypes.length <= 1000 1 <= numberOfBoxesi, numberOfUnitsPerBoxi <= 1000 1 <= truckSize <= 106
[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 good meals you can make from this list modulo 109 + 7. Note that items with different indices are considered different even if they have the same deliciousness value. Example 1: Input: deliciousness = [1,3,5,7,9] Output: 4 Explanation: The good meals are (1,3), (1,7), (3,5) and, (7,9). Their respective sums are 4, 8, 8, and 16, all of which are powers of 2. Example 2: Input: deliciousness = [1,1,1,3,3,3,7] Output: 15 Explanation: The good meals are (1,1) with 3 ways, (1,3) with 9 ways, and (1,7) with 3 ways. Constraints: 1 <= deliciousness.length <= 105 0 <= deliciousness[i] <= 220
[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) ans += max(0, min(len(nums), k) - max(i+1, j)) return ans % 1_000_000_007
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 the elements in right. Given nums, an array of non-negative integers, return the number of good ways to split nums. As the number may be too large, return it modulo 109 + 7. Example 1: Input: nums = [1,1,1] Output: 1 Explanation: The only good way to split nums is [1] [1] [1]. Example 2: Input: nums = [1,2,2,2,5,0] Output: 3 Explanation: There are three good ways of splitting nums: [1] [2] [2,2,5,0] [1] [2,2] [2,5,0] [1,2] [2,2] [5,0] Example 3: Input: nums = [3,2,1] Output: 0 Explanation: There is no good way to split nums. Constraints: 3 <= nums.length <= 105 0 <= nums[i] <= 104
[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] else: stack.append(loc[x]) return len(target) - len(stack)
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 very beginning or end of the array. Return the minimum number of operations needed to make target a subsequence of arr. A subsequence of an array is a new array generated from the original array by deleting some elements (possibly none) without changing the remaining elements' relative order. For example, [2,7,4] is a subsequence of [4,2,3,7,2,1,4] (the underlined elements), while [2,4,2] is not. Example 1: Input: target = [5,1,3], arr = [9,4,2,3,4] Output: 2 Explanation: You can add 5 and 1 in such a way that makes arr = [5,9,4,1,2,3,4], then target will be a subsequence of arr. Example 2: Input: target = [6,4,8,1,3,2], arr = [4,7,6,2,3,8,6,1] Output: 3 Constraints: 1 <= target.length, arr.length <= 105 1 <= target[i], arr[i] <= 109 target contains no duplicates.
[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 total amount of money he will have in the Leetcode bank at the end of the nth day. Example 1: Input: n = 4 Output: 10 Explanation: After the 4th day, the total is 1 + 2 + 3 + 4 = 10. Example 2: Input: n = 10 Output: 37 Explanation: After the 10th day, the total is (1 + 2 + 3 + 4 + 5 + 6 + 7) + (2 + 3 + 4) = 37. Notice that on the 2nd Monday, Hercy only puts in $2. Example 3: Input: n = 20 Output: 96 Explanation: After the 20th day, the total is (1 + 2 + 3 + 4 + 5 + 6 + 7) + (2 + 3 + 4 + 5 + 6 + 7 + 8) + (3 + 4 + 5 + 6 + 7 + 8) = 96. Constraints: 1 <= n <= 1000
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 < len(s): stack.append(s[i]) n = len(stack) prefix = stack[n-2] + stack[n-1] # if see the prefix ab or ba move from stack and increment the answer if prefix == word: answer += x stack.pop() stack.pop() i += 1 # change the x point to y for 2nd iteration x = y # assign new letters with already removed prefix s = ''.join(stack) return answer
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 "cabxe". Return the maximum points you can gain after applying the above operations on s. Example 1: Input: s = "cdbcbbaaabab", x = 4, y = 5 Output: 19 Explanation: - Remove the "ba" underlined in "cdbcbbaaabab". Now, s = "cdbcbbaaab" and 5 points are added to the score. - Remove the "ab" underlined in "cdbcbbaaab". Now, s = "cdbcbbaa" and 4 points are added to the score. - Remove the "ba" underlined in "cdbcbbaa". Now, s = "cdbcba" and 5 points are added to the score. - Remove the "ba" underlined in "cdbcba". Now, s = "cdbc" and 5 points are added to the score. Total score = 5 + 4 + 5 + 5 = 19. Example 2: Input: s = "aabbaaxybbaabb", x = 5, y = 4 Output: 20 Constraints: 1 <= s.length <= 105 1 <= x, y <= 104 s consists of lowercase English letters.
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 used that number # backtracking def dfs(arr, i, vi): # if we already fill the array successfully, return True if i >= (2*n-1): return True # try each number from n to 1 for x in range(n, 0, -1): # two cases: # x > 1, we check two places. Mind index out of bound here. # x = 1, we only check one place # arr[i] == 0 means index i is not occupied if (x > 1 and ((not (arr[i] == 0 and (i+x < 2*n-1) and arr[i+x] == 0)) or vi[x])) \ or (x == 1 and (arr[i] != 0 or vi[x])): continue # if it can be placed, then place it if x > 1: arr[i] = x arr[i+x] = x else: arr[i] = x vi[x] = True # find the next available place nexti = i+1 while nexti < 2*n-1 and arr[nexti]: nexti += 1 # place the next one if dfs(arr, nexti, vi): # if it success, it is already the lexicographically largest one, we don't search anymore return True # backtracking... restore the state if x > 1: arr[i] = 0 arr[i+x] = 0 else: arr[i] = 0 vi[x] = False # we could not find a solution, return False return False dfs(arr, i, vi) return arr
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, a[i] and a[j], is the absolute difference of their indices, |j - i|. Return the lexicographically largest sequence. It is guaranteed that under the given constraints, there is always a solution. A sequence a is lexicographically larger than a sequence b (of the same length) if in the first position where a and b differ, sequence a has a number greater than the corresponding number in b. For example, [0,1,9,0] is lexicographically larger than [0,1,5,6] because the first position they differ is at the third number, and 9 is greater than 5. Example 1: Input: n = 3 Output: [3,1,2,3,2] Explanation: [2,3,2,1,3] is also a valid sequence, but [3,1,2,3,2] is the lexicographically largest valid sequence. Example 2: Input: n = 5 Output: [5,3,1,4,3,5,2,4,2] Constraints: 1 <= n <= 20
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]), reverse=True): p = min(ancestors &amp; graph[n], key=lambda x: len(graph[x]), default=None) # immediate ancestor ancestors.add(n) if p: if graph[n] - (graph[p] | {p}): return 0 # impossible to have more than ancestor if len(graph[n]) == len(graph[p]): ans = 2 elif len(graph[n]) != len(graph)-1: return 0 return ans
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 ancestor of xi. Note: the tree does not have to be a binary tree. Two ways are considered to be different if there is at least one node that has different parents in both ways. Return: 0 if ways == 0 1 if ways == 1 2 if ways > 1 A rooted tree is a tree that has a single root node, and all edges are oriented to be outgoing from the root. An ancestor of a node is any node on the path from the root to that node (excluding the node itself). The root has no ancestors. Example 1: Input: pairs = [[1,2],[2,3]] Output: 1 Explanation: There is exactly one valid rooted tree, which is shown in the above figure. Example 2: Input: pairs = [[1,2],[2,3],[1,3]] Output: 2 Explanation: There are multiple valid rooted trees. Three of them are shown in the above figures. Example 3: Input: pairs = [[1,2],[2,3],[2,4],[1,5]] Output: 0 Explanation: There are no valid rooted trees. Constraints: 1 <= pairs.length <= 105 1 <= xi < yi <= 500 The elements in pairs are unique.
[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, that is the first element of arr, i.e. arr[0]. Return the original array arr. It can be proved that the answer exists and is unique. Example 1: Input: encoded = [1,2,3], first = 1 Output: [1,0,2,1] Explanation: If arr = [1,0,2,1], then first = 1 and encoded = [1 XOR 0, 0 XOR 2, 2 XOR 1] = [1,2,3] Example 2: Input: encoded = [6,2,7,3], first = 4 Output: [4,2,0,7,4] Constraints: 2 <= n <= 104 encoded.length == n - 1 0 <= encoded[i] <= 105 0 <= first <= 105
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,5], k = 5 Output: [7,9,6,6,8,7,3,0,9,5] Constraints: The number of nodes in the list is n. 1 <= k <= n <= 105 0 <= Node.val <= 100
[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) adj[b].append(a) return adj def dfs(i): visited.add(i) this_group.add(i) for neigh in adj[i]: if neigh not in visited: dfs(neigh) adj = gen_adjacency() visited = set() common_counts = 0 for i in adj: if i not in visited: this_group = set() dfs(i) s_counts = collections.Counter([source[i] for i in this_group]) t_counts = collections.Counter([target[i] for i in this_group]) common = set(s_counts).intersection(t_counts) for common_int in common: common_counts += min(s_counts[common_int], t_counts[common_int]) ans = len(source) - common_counts return ans
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 multiple times and in any order. The Hamming distance of two arrays of the same length, source and target, is the number of positions where the elements are different. Formally, it is the number of indices i for 0 <= i <= n-1 where source[i] != target[i] (0-indexed). Return the minimum Hamming distance of source and target after performing any amount of swap operations on array source. Example 1: Input: source = [1,2,3,4], target = [2,1,4,5], allowedSwaps = [[0,1],[2,3]] Output: 1 Explanation: source can be transformed the following way: - Swap indices 0 and 1: source = [2,1,3,4] - Swap indices 2 and 3: source = [2,1,4,3] The Hamming distance of source and target is 1 as they differ in 1 position: index 3. Example 2: Input: source = [1,2,3,4], target = [1,3,2,4], allowedSwaps = [] Output: 2 Explanation: There are no allowed swaps. The Hamming distance of source and target is 2 as they differ in 2 positions: index 1 and index 2. Example 3: Input: source = [5,1,2,4,3], target = [1,5,4,2,3], allowedSwaps = [[0,4],[4,2],[1,3],[1,4]] Output: 0 Constraints: n == source.length == target.length 1 <= n <= 105 1 <= source[i], target[i] <= 105 0 <= allowedSwaps.length <= 105 allowedSwaps[i].length == 2 0 <= ai, bi <= n - 1 ai != bi
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 in range(k): if not kk or time[kk-1] > time[kk]: time[kk] += jobs[i] if max(time) < ans: fn(i+1) time[kk] -= jobs[i] ans = inf time = [0]*k fn(0) return ans
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 to devise an optimal assignment such that the maximum working time of any worker is minimized. Return the minimum possible maximum working time of any assignment. Example 1: Input: jobs = [3,2,3], k = 3 Output: 3 Explanation: By assigning each person one job, the maximum time is 3. Example 2: Input: jobs = [1,2,4,7,8], k = 2 Output: 11 Explanation: Assign the jobs the following way: Worker 1: 1, 2, 8 (working time = 1 + 2 + 8 = 11) Worker 2: 4, 7 (working time = 4 + 7 = 11) The maximum working time is 11. Constraints: 1 <= k <= jobs.length <= 12 1 <= jobs[i] <= 107
[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 most 4. Let maxLen be the side length of the largest square you can obtain from any of the given rectangles. Return the number of rectangles that can make a square with a side length of maxLen. Example 1: Input: rectangles = [[5,8],[3,9],[5,12],[16,5]] Output: 3 Explanation: The largest squares you can get from each rectangle are of lengths [5,3,5,5]. The largest possible square is of length 5, and you can get it out of 3 rectangles. Example 2: Input: rectangles = [[2,3],[3,7],[4,3],[3,7]] Output: 3 Constraints: 1 <= rectangles.length <= 1000 rectangles[i].length == 2 1 <= li, wi <= 109 li != wi
[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) return 8*ans
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,6) , (4,3,2,6) , (3,4,6,2) , (4,3,6,2) Example 2: Input: nums = [1,2,4,5,10] Output: 16 Explanation: There are 16 valid tuples: (1,10,2,5) , (1,10,5,2) , (10,1,2,5) , (10,1,5,2) (2,5,1,10) , (2,5,10,1) , (5,2,1,10) , (5,2,10,1) (2,10,4,5) , (2,10,5,4) , (10,2,4,5) , (10,2,5,4) (4,5,2,10) , (4,5,10,2) , (5,4,2,10) , (5,4,10,2) Constraints: 1 <= nums.length <= 1000 1 <= nums[i] <= 104 All elements in nums are distinct.
[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): matrix[i].sort(reverse=1) for j in range(n): ans = max(ans, (j+1)*matrix[i][j]) return ans
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]] Output: 4 Explanation: You can rearrange the columns as shown above. The largest submatrix of 1s, in bold, has an area of 4. Example 2: Input: matrix = [[1,0,1,0,1]] Output: 3 Explanation: You can rearrange the columns as shown above. The largest submatrix of 1s, in bold, has an area of 3. Example 3: Input: matrix = [[1,1,0],[1,0,1]] Output: 2 Explanation: Notice that you must rearrange entire columns, and there is no way to make a submatrix of 1s larger than an area of 2. Constraints: m == matrix.length n == matrix[i].length 1 <= m * n <= 105 matrix[i][j] is either 0 or 1.
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 for i in range(m): for j in range(n): if grid[i][j] != '#': available += 1 if grid[i][j] == 'M': mouse_pos = (i, j) elif grid[i][j] == 'C': cat_pos = (i, j) @functools.lru_cache(None) def dp(turn, mouse_pos, cat_pos): # if turn == m * n * 2: # We already search the whole grid (9372 ms 74.3 MB) if turn == available * 2: # We already search the whole touchable grid (5200 ms 57.5 MB) return False if turn % 2 == 0: # Mouse i, j = mouse_pos for di, dj in dirs: for jump in range(mouseJump + 1): # Note that we want to do range(mouseJump + 1) instead of range(1, mouseJump + 1) # considering the case that we can stay at the same postion for next turn. new_i, new_j = i + di * jump, j + dj * jump if 0 <= new_i < m and 0 <= new_j < n and grid[new_i][new_j] != '#': # Valid pos if dp(turn + 1, (new_i, new_j), cat_pos) or grid[new_i][new_j] == 'F': return True else: # Stop extending the jump since we cannot go further break return False else: # Cat i, j = cat_pos for di, dj in dirs: for jump in range(catJump + 1): new_i, new_j = i + di * jump, j + dj * jump if 0 <= new_i < m and 0 <= new_j < n and grid[new_i][new_j] != '#': if not dp(turn + 1, mouse_pos, (new_i, new_j)) or (new_i, new_j) == mouse_pos or grid[new_i][new_j] == 'F': # This condition will also handle the case that the cat cannot jump through the mouse return False else: break return True return dp(0, mouse_pos, cat_pos)
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. Walls are represented by the character '#' and cannot be walked on. Food is represented by the character 'F' and can be walked on. There is only one of each character 'C', 'M', and 'F' in grid. Mouse and Cat play according to the following rules: Mouse moves first, then they take turns to move. During each turn, Cat and Mouse can jump in one of the four directions (left, right, up, down). They cannot jump over the wall nor outside of the grid. catJump, mouseJump are the maximum lengths Cat and Mouse can jump at a time, respectively. Cat and Mouse can jump less than the maximum length. Staying in the same position is allowed. Mouse can jump over Cat. The game can end in 4 ways: If Cat occupies the same position as Mouse, Cat wins. If Cat reaches the food first, Cat wins. If Mouse reaches the food first, Mouse wins. If Mouse cannot get to the food within 1000 turns, Cat wins. Given a rows x cols matrix grid and two integers catJump and mouseJump, return true if Mouse can win the game if both Cat and Mouse play optimally, otherwise return false. Example 1: Input: grid = ["####F","#C...","M...."], catJump = 1, mouseJump = 2 Output: true Explanation: Cat cannot catch Mouse on its turn nor can it get the food before Mouse. Example 2: Input: grid = ["M.C...F"], catJump = 1, mouseJump = 4 Output: true Example 3: Input: grid = ["M.C...F"], catJump = 1, mouseJump = 3 Output: false Constraints: rows == grid.length cols = grid[i].length 1 <= rows, cols <= 8 grid[i][j] consist only of characters 'C', 'M', 'F', '.', and '#'. There is only one of each character 'C', 'M', and 'F' in grid. 1 <= catJump, mouseJump <= 8
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 through each of the gains for g in gain: #updating the current altitude based on the gain current_altitude += g #if the current altitude is greater than the highest altitude recorded then assign it as the result. This done iteratively, allows us to find the highest altitude if current_altitude > result: result = current_altitude return result
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 altitude of a point. Example 1: Input: gain = [-5,1,5,0,-7] Output: 1 Explanation: The altitudes are [0,-5,-4,1,1,-6]. The highest is 1. Example 2: Input: gain = [-4,-3,-2,-1,4,3,2] Output: 0 Explanation: The altitudes are [0,-4,-7,-9,-10,-6,-3,-1]. The highest is 0. Constraints: n == gain.length 1 <= n <= 100 -100 <= gain[i] <= 100
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]: for i in range(n): if i+1 not in languages[u-1]: mp.setdefault(u-1, set()).add(i) if i+1 not in languages[v-1]: mp.setdefault(v-1, set()).add(i) ans = inf for i in range(n): val = 0 for k in range(m): if i in mp.get(k, set()): val += 1 ans = min(ans, val) return ans
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 user knows, and friendships[i] = [ui, vi] denotes a friendship between the users ui and vi. You can choose one language and teach it to some users so that all friends can communicate with each other. Return the minimum number of users you need to teach. Note that friendships are not transitive, meaning if x is a friend of y and y is a friend of z, this doesn't guarantee that x is a friend of z. Example 1: Input: n = 2, languages = [[1],[2],[1,2]], friendships = [[1,2],[1,3],[2,3]] Output: 1 Explanation: You can either teach user 1 the second language or user 2 the first language. Example 2: Input: n = 3, languages = [[2],[1,3],[1,2],[3]], friendships = [[1,4],[1,2],[3,4],[2,3]] Output: 2 Explanation: Teach the third language to users 1 and 3, yielding two users to teach. Constraints: 2 <= n <= 500 languages.length == m 1 <= m <= 500 1 <= languages[i].length <= n 1 <= languages[i][j] <= n 1 <= ui < vi <= languages.length 1 <= friendships.length <= 500 All tuples (ui, vi) are unique languages[i] contains only unique values
[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 range(1,n): res[j] = res[j-1]^encoded[j-1] return res
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 original array perm. It is guaranteed that the answer exists and is unique. Example 1: Input: encoded = [3,1] Output: [1,2,3] Explanation: If perm = [1,2,3], then encoded = [1 XOR 2,2 XOR 3] = [3,1] Example 2: Input: encoded = [6,5,4,6] Output: [2,4,1,5,3] Constraints: 3 <= n < 105 n is odd. encoded.length == n - 1
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): if k % factor == 0: ways += dp(n-1, k//factor) # or take the '3' part ways %= (10**9+7) return ways % (10**9+7) res = [0] * len(queries) for i,(n, k) in enumerate(queries): res[i] = dp(n,k) return res # better solution -> find out how many prime factors a number has. # how many ways to group P numbers into N groups (since array has N values only) # but you can group in lesser groups and keep 1 1 1 1 as padding in array :(
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 modulo 109 + 7. Return an integer array answer where answer.length == queries.length, and answer[i] is the answer to the ith query. Example 1: Input: queries = [[2,6],[5,1],[73,660]] Output: [4,1,50734910] Explanation: Each query is independent. [2,6]: There are 4 ways to fill an array of size 2 that multiply to 6: [1,6], [2,3], [3,2], [6,1]. [5,1]: There is 1 way to fill an array of size 5 that multiply to 1: [1,1,1,1,1]. [73,660]: There are 1050734917 ways to fill an array of size 73 that multiply to 660. 1050734917 modulo 109 + 7 = 50734910. Example 2: Input: queries = [[1,1],[2,2],[3,3],[4,4],[5,5]] Output: [1,2,3,10,5] Constraints: 1 <= queries.length <= 104 1 <= ni, ki <= 104
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 i == 3: time[i] = "5" else: time[i] = "9" return "".join(time)
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" Explanation: The latest hour beginning with the digit '2' is 23 and the latest minute ending with the digit '0' is 50. Example 2: Input: time = "0?:3?" Output: "09:39" Example 3: Input: time = "1?:22" Output: "19:22" Constraints: time is in the format hh:mm. It is guaranteed that you can produce a valid time from the given string.
[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] pb[i+1] += pb[i] ans = min(ans, pa[i] + len(b) - pb[i]) # condition 2 ans = min(ans, len(a) - pa[i] + pb[i]) # condition 1 return ans
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 less than every letter in a in the alphabet. Both a and b consist of only one distinct letter. Return the minimum number of operations needed to achieve your goal. Example 1: Input: a = "aba", b = "caa" Output: 2 Explanation: Consider the best way to make each condition true: 1) Change b to "ccc" in 2 operations, then every letter in a is less than every letter in b. 2) Change a to "bbb" and b to "aaa" in 3 operations, then every letter in b is less than every letter in a. 3) Change a to "aaa" and b to "aaa" in 2 operations, then a and b consist of one distinct letter. The best way was done in 2 operations (either condition 1 or condition 3). Example 2: Input: a = "dabadd", b = "cda" Output: 3 Explanation: The best way is to make condition 1 true by changing b to "eee". Constraints: 1 <= a.length, b.length <= 105 a and b consist only of lowercase letters.
[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] ^= matrix[i][j-1] if i and j: matrix[i][j] ^= matrix[i-1][j-1] ans.append(matrix[i][j]) return sorted(ans)[-k]
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. Example 1: Input: matrix = [[5,2],[1,6]], k = 1 Output: 7 Explanation: The value of coordinate (0,1) is 5 XOR 2 = 7, which is the largest value. Example 2: Input: matrix = [[5,2],[1,6]], k = 2 Output: 5 Explanation: The value of coordinate (0,0) is 5 = 5, which is the 2nd largest value. Example 3: Input: matrix = [[5,2],[1,6]], k = 3 Output: 4 Explanation: The value of coordinate (1,0) is 5 XOR 1 = 4, which is the 3rd largest value. Constraints: m == matrix.length n == matrix[i].length 1 <= m, n <= 1000 0 <= matrix[i][j] <= 106 1 <= k <= m * n
[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 the box y, then each side of the four vertical sides of the box y must either be adjacent to another box or to a wall. Given an integer n, return the minimum possible number of boxes touching the floor. Example 1: Input: n = 3 Output: 3 Explanation: The figure above is for the placement of the three boxes. These boxes are placed in the corner of the room, where the corner is on the left side. Example 2: Input: n = 4 Output: 3 Explanation: The figure above is for the placement of the four boxes. These boxes are placed in the corner of the room, where the corner is on the left side. Example 3: Input: n = 10 Output: 6 Explanation: The figure above is for the placement of the ten boxes. These boxes are placed in the corner of the room, where the corner is on the back side. Constraints: 1 <= n <= 109
[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 number. For example, the ball number 321 will be put in the box number 3 + 2 + 1 = 6 and the ball number 10 will be put in the box number 1 + 0 = 1. Given two integers lowLimit and highLimit, return the number of balls in the box with the most balls. Example 1: Input: lowLimit = 1, highLimit = 10 Output: 2 Explanation: Box Number: 1 2 3 4 5 6 7 8 9 10 11 ... Ball Count: 2 1 1 1 1 1 1 1 1 0 0 ... Box 1 has the most number of balls with 2 balls. Example 2: Input: lowLimit = 5, highLimit = 15 Output: 2 Explanation: Box Number: 1 2 3 4 5 6 7 8 9 10 11 ... Ball Count: 1 1 1 1 2 2 1 1 1 0 0 ... Boxes 5 and 6 have the most number of balls with 2 balls in each. Example 3: Input: lowLimit = 19, highLimit = 28 Output: 2 Explanation: Box Number: 1 2 3 4 5 6 7 8 9 10 11 12 ... Ball Count: 0 1 1 1 1 1 1 1 1 2 0 0 ... Box 10 has the most number of balls with 2 balls. Constraints: 1 <= lowLimit <= highLimit <= 105
[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 graph if len(graph[x]) == 1)] while stack: n = stack.pop() ans.append(n) seen.add(n) for nn in graph[n]: if nn not in seen: stack.append(nn) return ans
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. It is guaranteed that every adjacent pair of elements nums[i] and nums[i+1] will exist in adjacentPairs, either as [nums[i], nums[i+1]] or [nums[i+1], nums[i]]. The pairs can appear in any order. Return the original array nums. If there are multiple solutions, return any of them. Example 1: Input: adjacentPairs = [[2,1],[3,4],[3,2]] Output: [1,2,3,4] Explanation: This array has all its adjacent pairs in adjacentPairs. Notice that adjacentPairs[i] may not be in left-to-right order. Example 2: Input: adjacentPairs = [[4,-2],[1,4],[-3,1]] Output: [-2,4,1,-3] Explanation: There can be negative numbers. Another solution is [-3,1,4,-2], which would also be accepted. Example 3: Input: adjacentPairs = [[100000,-100000]] Output: [100000,-100000] Constraints: nums.length == n adjacentPairs.length == n - 1 adjacentPairs[i].length == 2 2 <= n <= 105 -105 <= nums[i], ui, vi <= 105 There exists some nums that has adjacentPairs as its pairs.
[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 day 0. You cannot eat any candy of type i unless you have eaten all candies of type i - 1. You must eat at least one candy per day until you have eaten all the candies. Construct a boolean array answer such that answer.length == queries.length and answer[i] is true if you can eat a candy of type favoriteTypei on day favoriteDayi without eating more than dailyCapi candies on any day, and false otherwise. Note that you can eat different types of candy on the same day, provided that you follow rule 2. Return the constructed array answer. Example 1: Input: candiesCount = [7,4,5,3,8], queries = [[0,2,2],[4,2,4],[2,13,1000000000]] Output: [true,false,true] Explanation: 1- If you eat 2 candies (type 0) on day 0 and 2 candies (type 0) on day 1, you will eat a candy of type 0 on day 2. 2- You can eat at most 4 candies each day. If you eat 4 candies every day, you will eat 4 candies (type 0) on day 0 and 4 candies (type 0 and type 1) on day 1. On day 2, you can only eat 4 candies (type 1 and type 2), so you cannot eat a candy of type 4 on day 2. 3- If you eat 1 candy each day, you will eat a candy of type 2 on day 13. Example 2: Input: candiesCount = [5,2,6,4,1], queries = [[3,1,2],[4,10,3],[3,10,100],[4,100,30],[1,3,1]] Output: [false,true,true,false,false] Constraints: 1 <= candiesCount.length <= 105 1 <= candiesCount[i] <= 105 1 <= queries.length <= 105 queries[i].length == 3 0 <= favoriteTypei < candiesCount.length 0 <= favoriteDayi <= 109 1 <= dailyCapi <= 109
[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 @lru_cache(None) def fn(i, k): """Return True if s[i:] can be split into k palindromic substrings.""" if k < 0: return False if i == len(s): return k == 0 return any(fn(ii+1, k-1) for ii in mp[i]) return fn(0, 3)
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 substrings are palindromes. Example 2: Input: s = "bcbddxy" Output: false Explanation: s cannot be split into 3 palindromes. Constraints: 3 <= s.length <= 2000 s consists only of lowercase English letters.
[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 return sum
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] Output: 0 Explanation: There are no unique elements, and the sum is 0. Example 3: Input: nums = [1,2,3,4,5] Output: 15 Explanation: The unique elements are [1,2,3,4,5], and the sum is 15. Constraints: 1 <= nums.length <= 100 1 <= nums[i] <= 100
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 is a non-negative integer, then abs(x) = x. Example 1: Input: nums = [1,-3,2,3,-4] Output: 5 Explanation: The subarray [2,3] has absolute sum = abs(2+3) = abs(5) = 5. Example 2: Input: nums = [2,-5,1,-4,3,-2] Output: 8 Explanation: The subarray [-5,1,-4] has absolute sum = abs(-5+1-4) = abs(-8) = 8. Constraints: 1 <= nums.length <= 105 -104 <= nums[i] <= 104
[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 suffix are equal. The prefix and the suffix should not intersect at any index. The characters from the prefix and suffix must be the same. Delete both the prefix and the suffix. Return the minimum length of s after performing the above operation any number of times (possibly zero times). Example 1: Input: s = "ca" Output: 2 Explanation: You can't remove any characters, so the string stays as is. Example 2: Input: s = "cabaabac" Output: 0 Explanation: An optimal sequence of operations is: - Take prefix = "c" and suffix = "c" and remove them, s = "abaaba". - Take prefix = "a" and suffix = "a" and remove them, s = "baab". - Take prefix = "b" and suffix = "b" and remove them, s = "aa". - Take prefix = "a" and suffix = "a" and remove them, s = "". Example 3: Input: s = "aabccabba" Output: 3 Explanation: An optimal sequence of operations is: - Take prefix = "aa" and suffix = "a" and remove them, s = "bccabb". - Take prefix = "b" and suffix = "bb" and remove them, s = "cca". Constraints: 1 <= s.length <= 105 s only consists of characters 'a', 'b', and 'c'.
[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 END TIME # event_index is the current event we are checking @lru_cache(None) def dp(end: int, event_index: int, k: int): # No more events left or we have checked all possible events if k == 0 or event_index == n: return 0 event = events[event_index] event_start, event_end, event_value = event # Can we attend this event? # Does its start time conflict with the previous events end time? # If the start time is the same as the end time we cannot end as well (view example 2) if event_start <= end: # Could not attend, check the next event return dp(end, event_index + 1, k) # We made it here, so we can attend! # Two possible options, we either attend (add the value) or do not attend this event # Value for attending versus the value for skipping attend = event_value + dp(event_end, event_index + 1, k - 1) skip = dp(end, event_index + 1, k) # Get the best option return max(attend, skip) # Clear cache to save memory dp.cache_clear() return dp(0, 0, k)
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 event at a time. If you choose to attend an event, you must attend the entire event. Note that the end day is inclusive: that is, you cannot attend two events where one of them starts and the other ends on the same day. Return the maximum sum of values that you can receive by attending events. Example 1: Input: events = [[1,2,4],[3,4,3],[2,3,1]], k = 2 Output: 7 Explanation: Choose the green events, 0 and 1 (0-indexed) for a total value of 4 + 3 = 7. Example 2: Input: events = [[1,2,4],[3,4,3],[2,3,10]], k = 2 Output: 10 Explanation: Choose event 2 for a total value of 10. Notice that you cannot attend any other event as they overlap, and that you do not have to attend k events. Example 3: Input: events = [[1,1,1],[2,2,2],[3,3,3],[4,4,4]], k = 3 Output: 9 Explanation: Although the events do not overlap, you can only attend 3 events. Pick the highest valued three. Constraints: 1 <= k <= events.length 1 <= k * events.length <= 106 1 <= startDayi <= endDayi <= 109 1 <= valuei <= 106
[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 and e>rotated[i+1]: # check that rerotated array sorted or not return False return True
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] == B[(i+x) % A.length], where % is the modulo operation. Example 1: Input: nums = [3,4,5,1,2] Output: true Explanation: [1,2,3,4,5] is the original sorted array. You can rotate the array by x = 3 positions to begin on the the element of value 3: [3,4,5,1,2]. Example 2: Input: nums = [2,1,3,4] Output: false Explanation: There is no sorted array once rotated that can make nums. Example 3: Input: nums = [1,2,3] Output: true Explanation: [1,2,3] is the original sorted array. You can rotate the array by x = 0 positions (i.e. no rotation) to make nums. Constraints: 1 <= nums.length <= 100 1 <= nums[i] <= 100
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 three integers a, b, and c, return the maximum score you can get. Example 1: Input: a = 2, b = 4, c = 6 Output: 6 Explanation: The starting state is (2, 4, 6). One optimal set of moves is: - Take from 1st and 3rd piles, state is now (1, 4, 5) - Take from 1st and 3rd piles, state is now (0, 4, 4) - Take from 2nd and 3rd piles, state is now (0, 3, 3) - Take from 2nd and 3rd piles, state is now (0, 2, 2) - Take from 2nd and 3rd piles, state is now (0, 1, 1) - Take from 2nd and 3rd piles, state is now (0, 0, 0) There are fewer than two non-empty piles, so the game ends. Total: 6 points. Example 2: Input: a = 4, b = 4, c = 6 Output: 7 Explanation: The starting state is (4, 4, 6). One optimal set of moves is: - Take from 1st and 2nd piles, state is now (3, 3, 6) - Take from 1st and 3rd piles, state is now (2, 3, 5) - Take from 1st and 3rd piles, state is now (1, 3, 4) - Take from 1st and 3rd piles, state is now (0, 3, 3) - Take from 2nd and 3rd piles, state is now (0, 2, 2) - Take from 2nd and 3rd piles, state is now (0, 1, 1) - Take from 2nd and 3rd piles, state is now (0, 0, 0) There are fewer than two non-empty piles, so the game ends. Total: 7 points. Example 3: Input: a = 1, b = 8, c = 8 Output: 8 Explanation: One optimal set of moves is to take from the 2nd and 3rd piles for 8 turns until they are empty. After that, there are fewer than two non-empty piles, so the game ends. Constraints: 1 <= a, b, c <= 105
[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[i2]) i2 += 1 return "".join(ans) + word1[i1:] + word2[i2:]
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 = "dv", then after choosing this operation, word1 = "bc" and merge = "dva". If word2 is non-empty, append the first character in word2 to merge and delete it from word2. For example, if word2 = "abc" and merge = "", then after choosing this operation, word2 = "bc" and merge = "a". Return the lexicographically largest merge you can construct. A string a is lexicographically larger than a string b (of the same length) if in the first position where a and b differ, a has a character strictly larger than the corresponding character in b. For example, "abcd" is lexicographically larger than "abcc" because the first position they differ is at the fourth character, and d is greater than c. Example 1: Input: word1 = "cabaa", word2 = "bcaaa" Output: "cbcabaaaaa" Explanation: One way to get the lexicographically largest merge is: - Take from word1: merge = "c", word1 = "abaa", word2 = "bcaaa" - Take from word2: merge = "cb", word1 = "abaa", word2 = "caaa" - Take from word2: merge = "cbc", word1 = "abaa", word2 = "aaa" - Take from word1: merge = "cbca", word1 = "baa", word2 = "aaa" - Take from word1: merge = "cbcab", word1 = "aa", word2 = "aaa" - Append the remaining 5 a's from word1 and word2 at the end of merge. Example 2: Input: word1 = "abcabc", word2 = "abdcaba" Output: "abdcabcabcaba" Constraints: 1 <= word1.length, word2.length <= 3000 word1 and word2 consist only of lowercase English letters.
[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 for x in fn(nums[len(nums)//2:]): k = bisect_left(nums0, goal - x) if k < len(nums0): ans = min(ans, nums0[k] + x - goal) if 0 < k: ans = min(ans, goal - x - nums0[k-1]) return ans
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 value of abs(sum - goal). Note that a subsequence of an array is an array formed by removing some elements (possibly all or none) of the original array. Example 1: Input: nums = [5,-7,3,5], goal = 6 Output: 0 Explanation: Choose the whole array as a subsequence, with a sum of 6. This is equal to the goal, so the absolute difference is 0. Example 2: Input: nums = [7,-9,15,-2], goal = -5 Output: 1 Explanation: Choose the subsequence [7,-9,-2], with a sum of -4. The absolute difference is abs(-4 - (-5)) = abs(1) = 1, which is the minimum. Example 3: Input: nums = [1,2,3], goal = -7 Output: 7 Constraints: 1 <= nums.length <= 40 -107 <= nums[i] <= 107 -109 <= goal <= 109
[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 s[i] == '0': count += 1 if s[i] == '1': count1 += 1 return min(count, count1)
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 operations needed to make s alternating. Example 1: Input: s = "0100" Output: 1 Explanation: If you change the last character to '1', s will be "0101", which is alternating. Example 2: Input: s = "10" Output: 0 Explanation: s is already alternating. Example 3: Input: s = "1111" Output: 2 Explanation: You need two operations to reach "0101" or "1010". Constraints: 1 <= s.length <= 104 s[i] is either '0' or '1'.
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: res+=(count*(count-1)//2) return (res+n)%(10**9+7)
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 Explanation: The homogenous substrings are listed as below: "a" appears 3 times. "aa" appears 1 time. "b" appears 2 times. "bb" appears 1 time. "c" appears 3 times. "cc" appears 2 times. "ccc" appears 1 time. 3 + 1 + 2 + 1 + 3 + 2 + 1 = 13. Example 2: Input: s = "xy" Output: 2 Explanation: The homogenous substrings are "x" and "y". Example 3: Input: s = "zzzzz" Output: 15 Constraints: 1 <= s.length <= 105 s consists of lowercase letters.
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 two new bags of 1 and 4 balls, or two new bags of 2 and 3 balls. Your penalty is the maximum number of balls in a bag. You want to minimize your penalty after the operations. Return the minimum possible penalty after performing the operations. Example 1: Input: nums = [9], maxOperations = 2 Output: 3 Explanation: - Divide the bag with 9 balls into two bags of sizes 6 and 3. [9] -> [6,3]. - Divide the bag with 6 balls into two bags of sizes 3 and 3. [6,3] -> [3,3,3]. The bag with the most number of balls has 3 balls, so your penalty is 3 and you should return 3. Example 2: Input: nums = [2,4,8,2], maxOperations = 4 Output: 2 Explanation: - Divide the bag with 8 balls into two bags of sizes 4 and 4. [2,4,8,2] -> [2,4,4,4,2]. - Divide the bag with 4 balls into two bags of sizes 2 and 2. [2,4,4,4,2] -> [2,2,2,4,4,2]. - Divide the bag with 4 balls into two bags of sizes 2 and 2. [2,2,2,4,4,2] -> [2,2,2,2,2,4,2]. - Divide the bag with 4 balls into two bags of sizes 2 and 2. [2,2,2,2,2,4,2] -> [2,2,2,2,2,2,2,2]. The bag with the most number of balls has 2 balls, so your penalty is 2, and you should return 2. Constraints: 1 <= nums.length <= 105 1 <= maxOperations, nums[i] <= 109
[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 ans = inf for i in range(n): for j in range(i+1, n): if graph[i][j]: for k in range(j+1, n): if graph[j][k] and graph[k][i]: ans = min(ans, degree[i] + degree[j] + degree[k] - 6) return ans if ans < inf else -1
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 of a connected trio is the number of edges where one endpoint is in the trio, and the other is not. Return the minimum degree of a connected trio in the graph, or -1 if the graph has no connected trios. Example 1: Input: n = 6, edges = [[1,2],[1,3],[3,2],[4,1],[5,2],[3,6]] Output: 3 Explanation: There is exactly one trio, which is [1,2,3]. The edges that form its degree are bolded in the figure above. Example 2: Input: n = 7, edges = [[1,3],[4,1],[4,3],[2,5],[5,6],[6,7],[7,5],[2,6]] Output: 0 Explanation: There are exactly three trios: 1) [1,4,3] with degree 0. 2) [2,5,6] with degree 2. 3) [5,6,7] with degree 2. Constraints: 2 <= n <= 400 edges[i].length == 2 1 <= edges.length <= n * (n-1) / 2 1 <= ui, vi <= n ui != vi There are no repeated edges.
[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 nice. If there are multiple, return the substring of the earliest occurrence. If there are none, return an empty string. Example 1: Input: s = "YazaAay" Output: "aAa" Explanation: "aAa" is a nice string because 'A/a' is the only letter of the alphabet in s, and both 'A' and 'a' appear. "aAa" is the longest nice substring. Example 2: Input: s = "Bb" Output: "Bb" Explanation: "Bb" is a nice string because both 'B' and 'b' appear. The whole string is a substring. Example 3: Input: s = "c" Output: "" Explanation: There are no nice substrings. Constraints: 1 <= s.length <= 100 s consists of uppercase and lowercase English letters.
[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 return True
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 subarrays must be in the same order as groups). Return true if you can do this task, and false otherwise. Note that the subarrays are disjoint if and only if there is no index k such that nums[k] belongs to more than one subarray. A subarray is a contiguous sequence of elements within an array. Example 1: Input: groups = [[1,-1,-1],[3,-2,0]], nums = [1,-1,0,1,-1,-1,3,-2,0] Output: true Explanation: You can choose the 0th subarray as [1,-1,0,1,-1,-1,3,-2,0] and the 1st one as [1,-1,0,1,-1,-1,3,-2,0]. These subarrays are disjoint as they share no common nums[k] element. Example 2: Input: groups = [[10,-2],[1,2,3,4]], nums = [1,2,3,4,10,-2] Output: false Explanation: Note that choosing the subarrays [1,2,3,4,10,-2] and [1,2,3,4,10,-2] is incorrect because they are not in the same order as in groups. [10,-2] must come before [1,2,3,4]. Example 3: Input: groups = [[1,2,3],[3,4]], nums = [7,7,1,2,3,4,7,7] Output: false Explanation: Note that choosing the subarrays [7,7,1,2,3,4,7,7] and [7,7,1,2,3,4,7,7] is invalid because they are not disjoint. They share a common elements nums[4] (0-indexed). Constraints: groups.length == n 1 <= n <= 103 1 <= groups[i].length, sum(groups[i].length) <= 103 1 <= nums.length <= 103 -107 <= groups[i][j], nums[k] <= 107
[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) while queue: newq = [] for i, j in queue: ans[i][j] = ht for ii, jj in (i-1, j), (i, j-1), (i, j+1), (i+1, j): if 0 <= ii < m and 0 <= jj < n and (ii, jj) not in seen: newq.append((ii, jj)) seen.add((ii, jj)) queue = newq ht += 1 return ans
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. If the cell is a water cell, its height must be 0. Any two adjacent cells must have an absolute height difference of at most 1. A cell is adjacent to another cell if the former is directly north, east, south, or west of the latter (i.e., their sides are touching). Find an assignment of heights such that the maximum height in the matrix is maximized. Return an integer matrix height of size m x n where height[i][j] is cell (i, j)'s height. If there are multiple solutions, return any of them. Example 1: Input: isWater = [[0,1],[0,0]] Output: [[1,0],[2,1]] Explanation: The image shows the assigned heights of each cell. The blue cell is the water cell, and the green cells are the land cells. Example 2: Input: isWater = [[0,0,1],[1,0,0],[0,0,0]] Output: [[1,1,0],[0,1,1],[1,2,2]] Explanation: A height of 2 is the maximum possible height of any assignment. Any height assignment that has a maximum height of 2 while still meeting the rules will also be accepted. Constraints: m == isWater.length n == isWater[i].length 1 <= m, n <= 1000 isWater[i][j] is 0 or 1. There is at least one water cell.
[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 -> list of position &amp; depth seen = {0} def fn(k, i): """Populate ans via dfs.""" ii = -1 for x in path: if gcd(nums[k], x) == 1: # coprime if path[x] and path[x][-1][1] > ii: ans[k] = path[x][-1][0] ii = path[x][-1][1] path.setdefault(nums[k], []).append((k, i)) for kk in tree.get(k, []): if kk not in seen: seen.add(kk) fn(kk, i+1) path[nums[k]].pop() fn(0, 0) return ans
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] represents the ith node's value, and each edges[j] = [uj, vj] represents an edge between nodes uj and vj in the tree. Two values x and y are coprime if gcd(x, y) == 1 where gcd(x, y) is the greatest common divisor of x and y. An ancestor of a node i is any other node on the shortest path from node i to the root. A node is not considered an ancestor of itself. Return an array ans of size n, where ans[i] is the closest ancestor to node i such that nums[i] and nums[ans[i]] are coprime, or -1 if there is no such ancestor. Example 1: Input: nums = [2,3,3,2], edges = [[0,1],[1,2],[1,3]] Output: [-1,0,0,1] Explanation: In the above figure, each node's value is in parentheses. - Node 0 has no coprime ancestors. - Node 1 has only one ancestor, node 0. Their values are coprime (gcd(2,3) == 1). - Node 2 has two ancestors, nodes 1 and 0. Node 1's value is not coprime (gcd(3,3) == 3), but node 0's value is (gcd(2,3) == 1), so node 0 is the closest valid ancestor. - Node 3 has two ancestors, nodes 1 and 0. It is coprime with node 1 (gcd(3,2) == 1), so node 1 is its closest valid ancestor. Example 2: Input: nums = [5,6,10,2,3,6,15], edges = [[0,1],[0,2],[1,3],[1,4],[2,5],[2,6]] Output: [-1,0,-1,0,0,0,-1] Constraints: nums.length == n 1 <= nums[i] <= 50 1 <= n <= 105 edges.length == n - 1 edges[j].length == 2 0 <= uj, vj < n uj != vj
[Python3] dfs
702
tree-of-coprimes
0.392
ye15
Hard
25,312
1,766