problem_title
stringlengths
3
77
python_solutions
stringlengths
81
8.45k
post_href
stringlengths
64
213
upvotes
int64
0
1.2k
question
stringlengths
0
3.6k
post_title
stringlengths
2
100
views
int64
1
60.9k
slug
stringlengths
3
77
acceptance
float64
0.14
0.91
user
stringlengths
3
26
difficulty
stringclasses
3 values
__index_level_0__
int64
0
34k
number
int64
1
2.48k
count nodes with the highest score
class Solution: def countHighestScoreNodes(self, parents: List[int]) -> int: graph = collections.defaultdict(list) for node, parent in enumerate(parents): # build graph graph[parent].append(node) n = len(parents) # total number of nodes d = collections.Counter() def count_nodes(node): # number of children node + self p, s = 1, 0 # p: product, s: sum for child in graph[node]: # for each child (only 2 at maximum) res = count_nodes(child) # get its nodes count p *= res # take the product s += res # take the sum p *= max(1, n - 1 - s) # times up-branch (number of nodes other than left, right children ans itself) d[p] += 1 # count the product return s + 1 # return number of children node + 1 (self) count_nodes(0) # starting from root (0) return d[max(d.keys())] # return max count
https://leetcode.com/problems/count-nodes-with-the-highest-score/discuss/1537603/Python-3-or-Graph-DFS-Post-order-Traversal-O(N)-or-Explanation
63
There is a binary tree rooted at 0 consisting of n nodes. The nodes are labeled from 0 to n - 1. You are given a 0-indexed integer array parents representing the tree, where parents[i] is the parent of node i. Since node 0 is the root, parents[0] == -1. Each node has a score. To find the score of a node, consider if the node and the edges connected to it were removed. The tree would become one or more non-empty subtrees. The size of a subtree is the number of the nodes in it. The score of the node is the product of the sizes of all those subtrees. Return the number of nodes that have the highest score. Example 1: Input: parents = [-1,2,0,2,0] Output: 3 Explanation: - The score of node 0 is: 3 * 1 = 3 - The score of node 1 is: 4 = 4 - The score of node 2 is: 1 * 1 * 2 = 2 - The score of node 3 is: 4 = 4 - The score of node 4 is: 4 = 4 The highest score is 4, and three nodes (node 1, node 3, and node 4) have the highest score. Example 2: Input: parents = [-1,2,0] Output: 2 Explanation: - The score of node 0 is: 2 = 2 - The score of node 1 is: 2 = 2 - The score of node 2 is: 1 * 1 = 1 The highest score is 2, and two nodes (node 0 and node 1) have the highest score. Constraints: n == parents.length 2 <= n <= 105 parents[0] == -1 0 <= parents[i] <= n - 1 for i != 0 parents represents a valid binary tree.
Python 3 | Graph, DFS, Post-order Traversal, O(N) | Explanation
3,300
count-nodes-with-the-highest-score
0.471
idontknoooo
Medium
28,444
2,049
parallel courses iii
class Solution: def minimumTime(self, n: int, relations: List[List[int]], time: List[int]) -> int: graph = { course:[] for course in range(n)} inDegree = [0]*n # 1- build graph # convert 1-base into 0-baseindexes and add to graph # Note: choose Prev->next since it helps to preserve the topology order for prevCourse,nextCourse in relations: prevCourse,nextCourse = prevCourse-1, nextCourse-1 graph[prevCourse].append(nextCourse) inDegree[nextCourse] += 1 # 2 Assign time cost q = collections.deque() cost = [0] * n for course in range(n): if inDegree[course] == 0: q.append(course) cost[course] = time[course] # number of months # 3- BFS while q: prevCourse = q.popleft() for nextCourse in graph[prevCourse]: # Update cost[nextCourse] using the maximum cost of the predecessor course cost[nextCourse] = max(cost[nextCourse], cost[prevCourse] + time[nextCourse]) inDegree[nextCourse] -= 1 if inDegree[nextCourse] == 0: q.append(nextCourse) return max(cost) ```
https://leetcode.com/problems/parallel-courses-iii/discuss/1546258/Python-solution-using-topology-sort-and-BFS
1
You are given an integer n, which indicates that there are n courses labeled from 1 to n. You are also given a 2D integer array relations where relations[j] = [prevCoursej, nextCoursej] denotes that course prevCoursej has to be completed before course nextCoursej (prerequisite relationship). Furthermore, you are given a 0-indexed integer array time where time[i] denotes how many months it takes to complete the (i+1)th course. You must find the minimum number of months needed to complete all the courses following these rules: You may start taking a course at any time if the prerequisites are met. Any number of courses can be taken at the same time. Return the minimum number of months needed to complete all the courses. Note: The test cases are generated such that it is possible to complete every course (i.e., the graph is a directed acyclic graph). Example 1: Input: n = 3, relations = [[1,3],[2,3]], time = [3,2,5] Output: 8 Explanation: The figure above represents the given graph and the time required to complete each course. We start course 1 and course 2 simultaneously at month 0. Course 1 takes 3 months and course 2 takes 2 months to complete respectively. Thus, the earliest time we can start course 3 is at month 3, and the total time required is 3 + 5 = 8 months. Example 2: Input: n = 5, relations = [[1,5],[2,5],[3,5],[3,4],[4,5]], time = [1,2,3,4,5] Output: 12 Explanation: The figure above represents the given graph and the time required to complete each course. You can start courses 1, 2, and 3 at month 0. You can complete them after 1, 2, and 3 months respectively. Course 4 can be taken only after course 3 is completed, i.e., after 3 months. It is completed after 3 + 4 = 7 months. Course 5 can be taken only after courses 1, 2, 3, and 4 have been completed, i.e., after max(1,2,3,7) = 7 months. Thus, the minimum time needed to complete all the courses is 7 + 5 = 12 months. Constraints: 1 <= n <= 5 * 104 0 <= relations.length <= min(n * (n - 1) / 2, 5 * 104) relations[j].length == 2 1 <= prevCoursej, nextCoursej <= n prevCoursej != nextCoursej All the pairs [prevCoursej, nextCoursej] are unique. time.length == n 1 <= time[i] <= 104 The given graph is a directed acyclic graph.
Python solution using topology sort and BFS
91
parallel-courses-iii
0.595
MAhmadian
Hard
28,452
2,050
kth distinct string in an array
class Solution: def kthDistinct(self, arr: List[str], k: int) -> str: freq = Counter(arr) for x in arr: if freq[x] == 1: k -= 1 if k == 0: return x return ""
https://leetcode.com/problems/kth-distinct-string-in-an-array/discuss/1549003/Python3-freq-table
19
A distinct string is a string that is present only once in an array. Given an array of strings arr, and an integer k, return the kth distinct string present in arr. If there are fewer than k distinct strings, return an empty string "". Note that the strings are considered in the order in which they appear in the array. Example 1: Input: arr = ["d","b","c","b","c","a"], k = 2 Output: "a" Explanation: The only distinct strings in arr are "d" and "a". "d" appears 1st, so it is the 1st distinct string. "a" appears 2nd, so it is the 2nd distinct string. Since k == 2, "a" is returned. Example 2: Input: arr = ["aaa","aa","a"], k = 1 Output: "aaa" Explanation: All strings in arr are distinct, so the 1st string "aaa" is returned. Example 3: Input: arr = ["a","b","a"], k = 3 Output: "" Explanation: The only distinct string is "b". Since there are fewer than 3 distinct strings, we return an empty string "". Constraints: 1 <= k <= arr.length <= 1000 1 <= arr[i].length <= 5 arr[i] consists of lowercase English letters.
[Python3] freq table
1,200
kth-distinct-string-in-an-array
0.718
ye15
Easy
28,458
2,053
two best non overlapping events
class Solution: def maxTwoEvents(self, events: List[List[int]]) -> int: events.sort() heap = [] res2,res1 = 0,0 for s,e,p in events: while heap and heap[0][0]<s: res1 = max(res1,heapq.heappop(heap)[1]) res2 = max(res2,res1+p) heapq.heappush(heap,(e,p)) return res2
https://leetcode.com/problems/two-best-non-overlapping-events/discuss/1549284/Heap-oror-very-Easy-oror-Well-Explained
13
You are given a 0-indexed 2D integer array of events where events[i] = [startTimei, endTimei, valuei]. The ith event starts at startTimei and ends at endTimei, and if you attend this event, you will receive a value of valuei. You can choose at most two non-overlapping events to attend such that the sum of their values is maximized. Return this maximum sum. Note that the start time and end time is inclusive: that is, you cannot attend two events where one of them starts and the other ends at the same time. More specifically, if you attend an event with end time t, the next event must start at or after t + 1. Example 1: Input: events = [[1,3,2],[4,5,2],[2,4,3]] Output: 4 Explanation: Choose the green events, 0 and 1 for a sum of 2 + 2 = 4. Example 2: Input: events = [[1,3,2],[4,5,2],[1,5,5]] Output: 5 Explanation: Choose event 2 for a sum of 5. Example 3: Input: events = [[1,5,3],[1,5,1],[6,6,5]] Output: 8 Explanation: Choose events 0 and 2 for a sum of 3 + 5 = 8. Constraints: 2 <= events.length <= 105 events[i].length == 3 1 <= startTimei <= endTimei <= 109 1 <= valuei <= 106
πŸ“ŒπŸ“Œ Heap || very-Easy || Well-Explained 🐍
502
two-best-non-overlapping-events
0.45
abhi9Rai
Medium
28,492
2,054
plates between candles
class Solution: def platesBetweenCandles(self, s: str, qs: List[List[int]]) -> List[int]: n=len(s) prefcandle=[-1]*n #this stores the position of closest candle from current towards left suffcandle=[0]*n #this stores the position of closest candle from current towards right pref=[0]*n #stores the number of plates till ith position from 0 - for i = 0 -> n ind=-1 c=0 #The following method calculates number of plates(*) till ith position from 0 - for i = 0 -> n for i in range(n): if ind!=-1 and s[i]=='*': c+=1 elif s[i]=='|': ind=i pref[i]=c #this method calculates the left nearest candle to a point #intial is -1 as to left of leftmost element no candle can be present ind =-1 for i in range(n): if s[i] == '|': ind=i prefcandle[i]=ind #this method calculates the right nearest candle to a point #intial is infinity as to right of rightmost element no candle can be present ind = float('inf') for i in range(n-1, -1, -1): if s[i]=='|': ind=i suffcandle[i]=ind #m = no of queries m=len(qs) ans=[0]*m for i in range(m): c=0 l=qs[i][0] r=qs[i][1] #check if left nearest candle of right boundary is after left boundary #check if right nearest candle of left boundary is before right boundary # to summarise - here we find if there is a pair of candle present within the given range or not if prefcandle[r]<l or suffcandle[l]>r: continue #desired answer is no of pplates(*) only inside 2 candles (|) inside the given boundary area ans[i]=pref[prefcandle[r]]-pref[suffcandle[l]] return ans
https://leetcode.com/problems/plates-between-candles/discuss/1549304/100-faster-Linear-Python-solution-or-Prefix-sum-or-O(N)
12
There is a long table with a line of plates and candles arranged on top of it. You are given a 0-indexed string s consisting of characters '*' and '|' only, where a '*' represents a plate and a '|' represents a candle. You are also given a 0-indexed 2D integer array queries where queries[i] = [lefti, righti] denotes the substring s[lefti...righti] (inclusive). For each query, you need to find the number of plates between candles that are in the substring. A plate is considered between candles if there is at least one candle to its left and at least one candle to its right in the substring. For example, s = "||**||**|*", and a query [3, 8] denotes the substring "*||**|". The number of plates between candles in this substring is 2, as each of the two plates has at least one candle in the substring to its left and right. Return an integer array answer where answer[i] is the answer to the ith query. Example 1: Input: s = "**|**|***|", queries = [[2,5],[5,9]] Output: [2,3] Explanation: - queries[0] has two plates between candles. - queries[1] has three plates between candles. Example 2: Input: s = "***|**|*****|**||**|*", queries = [[1,17],[4,5],[14,17],[5,11],[15,16]] Output: [9,0,0,0,0] Explanation: - queries[0] has nine plates between candles. - The other queries have zero plates between candles. Constraints: 3 <= s.length <= 105 s consists of '*' and '|' characters. 1 <= queries.length <= 105 queries[i].length == 2 0 <= lefti <= righti < s.length
100 % faster Linear Python solution | Prefix sum | O(N)
1,200
plates-between-candles
0.444
acloj97
Medium
28,496
2,055
number of valid move combinations on chessboard
class Solution: BOARD_SIZE = 8 def diag(self, r, c): # Return all diagonal indices except (r, c) # Diagonal indices has the same r - c inv = r - c result = [] for ri in range(self.BOARD_SIZE): ci = ri - inv if 0 <= ci < self.BOARD_SIZE and ri != r: result.append((ri, ci)) return result def reverseDiag(self, r, c): # Return all reverse diagonal indices except (r, c) # Reverse diagonal indices has the same r + c inv = r + c result = [] for ri in range(self.BOARD_SIZE): ci = inv - ri if 0 <= ci < self.BOARD_SIZE and ri != r: result.append((ri, ci)) return result def generatePossiblePositions(self, piece, start): # Generate list of possible positions for every figure rs, cs = start[0] - 1, start[1] - 1 # Start position result = [(rs, cs)] # Straight if piece == "rook" or piece == "queen": result.extend([(r, cs) for r in range(self.BOARD_SIZE) if r != rs]) result.extend([(rs, c) for c in range(self.BOARD_SIZE) if c != cs]) # Diagonal if piece == "bishop" or piece == "queen": result.extend(self.diag(rs, cs)) result.extend(self.reverseDiag(rs, cs)) return result def collide(self, start1, end1, start2, end2): # Check if two figures will collide # Collision occures if: # - two figures have the same end points # - one figure stands on the way of second one # # For this purpose let's model each step of two pieces # and compare their positions at every time step. def steps(start, end): # Total steps that should be done return abs(end - start) def step(start, end): # Step direction -1, 0, 1 if steps(start, end) == 0: return 0 return (end - start) / steps(start, end) (rstart1, cstart1), (rend1, cend1) = start1, end1 (rstart2, cstart2), (rend2, cend2) = start2, end2 # Find step direction for each piece rstep1, cstep1 = step(rstart1, rend1), step(cstart1, cend1) rstep2, cstep2 = step(rstart2, rend2), step(cstart2, cend2) # Find maximum number of steps for each piece max_step1 = max(steps(rstart1, rend1), steps(cstart1, cend1)) max_step2 = max(steps(rstart2, rend2), steps(cstart2, cend2)) # Move pieces step by step and compare their positions for step_i in range(max(max_step1, max_step2) + 1): step_i1 = min(step_i, max_step1) r1 = rstart1 + step_i1 * rstep1 c1 = cstart1 + step_i1 * cstep1 step_i2 = min(step_i, max_step2) r2 = rstart2 + step_i2 * rstep2 c2 = cstart2 + step_i2 * cstep2 # If positions are the same then collision occures if r1 == r2 and c1 == c2: return True return False def countCombinations(self, pieces: List[str], positions: List[List[int]]) -> int: if len(pieces) == 0: return 0 n = len(pieces) # Make zero-indexed start_positions = [[r - 1, c - 1] for r, c in positions] # All possible positions possible_positions = [ self.generatePossiblePositions(piece, start) for piece, start in zip(pieces, positions) ] # Let's use DFS with backtracking # For that we will keep set of already occupied coordinates # and current positions of pieces occupied = set() current_positions = [None] * n # None means that we didn't placed the piece def collision(start, end): # Helper to check if moving from start to end position will collide with someone for start2, end2 in zip(start_positions, current_positions): if end2 is not None and self.collide(start, end, start2, end2): return True return False def dfs(piece_i=0): # All pieces are placed if piece_i == n: return 1 result = 0 for position in possible_positions[piece_i]: # If position already occupied of collides with other pieces then skip it if position in occupied or collision(start_positions[piece_i], position): continue # Occupy the position occupied.add(position) current_positions[piece_i] = position # Run DFS for next piece result += dfs(piece_i + 1) # Release the position occupied.remove(position) current_positions[piece_i] = None return result return dfs()
https://leetcode.com/problems/number-of-valid-move-combinations-on-chessboard/discuss/2331905/Python3-or-DFS-with-backtracking-or-Clean-code-with-comments
1
There is an 8 x 8 chessboard containing n pieces (rooks, queens, or bishops). You are given a string array pieces of length n, where pieces[i] describes the type (rook, queen, or bishop) of the ith piece. In addition, you are given a 2D integer array positions also of length n, where positions[i] = [ri, ci] indicates that the ith piece is currently at the 1-based coordinate (ri, ci) on the chessboard. When making a move for a piece, you choose a destination square that the piece will travel toward and stop on. A rook can only travel horizontally or vertically from (r, c) to the direction of (r+1, c), (r-1, c), (r, c+1), or (r, c-1). A queen can only travel horizontally, vertically, or diagonally from (r, c) to the direction of (r+1, c), (r-1, c), (r, c+1), (r, c-1), (r+1, c+1), (r+1, c-1), (r-1, c+1), (r-1, c-1). A bishop can only travel diagonally from (r, c) to the direction of (r+1, c+1), (r+1, c-1), (r-1, c+1), (r-1, c-1). You must make a move for every piece on the board simultaneously. A move combination consists of all the moves performed on all the given pieces. Every second, each piece will instantaneously travel one square towards their destination if they are not already at it. All pieces start traveling at the 0th second. A move combination is invalid if, at a given time, two or more pieces occupy the same square. Return the number of valid move combinations. Notes: No two pieces will start in the same square. You may choose the square a piece is already on as its destination. If two pieces are directly adjacent to each other, it is valid for them to move past each other and swap positions in one second. Example 1: Input: pieces = ["rook"], positions = [[1,1]] Output: 15 Explanation: The image above shows the possible squares the piece can move to. Example 2: Input: pieces = ["queen"], positions = [[1,1]] Output: 22 Explanation: The image above shows the possible squares the piece can move to. Example 3: Input: pieces = ["bishop"], positions = [[4,3]] Output: 12 Explanation: The image above shows the possible squares the piece can move to. Constraints: n == pieces.length n == positions.length 1 <= n <= 4 pieces only contains the strings "rook", "queen", and "bishop". There will be at most one queen on the chessboard. 1 <= xi, yi <= 8 Each positions[i] is distinct.
Python3 | DFS with backtracking | Clean code with comments
58
number-of-valid-move-combinations-on-chessboard
0.59
snorkin
Hard
28,506
2,056
smallest index with equal value
class Solution: def smallestEqual(self, nums: List[int]) -> int: return next((i for i, x in enumerate(nums) if i%10 == x), -1)
https://leetcode.com/problems/smallest-index-with-equal-value/discuss/1549993/Python3-1-line
10
Given a 0-indexed integer array nums, return the smallest index i of nums such that i mod 10 == nums[i], or -1 if such index does not exist. x mod y denotes the remainder when x is divided by y. Example 1: Input: nums = [0,1,2] Output: 0 Explanation: i=0: 0 mod 10 = 0 == nums[0]. i=1: 1 mod 10 = 1 == nums[1]. i=2: 2 mod 10 = 2 == nums[2]. All indices have i mod 10 == nums[i], so we return the smallest index 0. Example 2: Input: nums = [4,3,2,1] Output: 2 Explanation: i=0: 0 mod 10 = 0 != nums[0]. i=1: 1 mod 10 = 1 != nums[1]. i=2: 2 mod 10 = 2 == nums[2]. i=3: 3 mod 10 = 3 != nums[3]. 2 is the only index which has i mod 10 == nums[i]. Example 3: Input: nums = [1,2,3,4,5,6,7,8,9,0] Output: -1 Explanation: No index satisfies i mod 10 == nums[i]. Constraints: 1 <= nums.length <= 100 0 <= nums[i] <= 9
[Python3] 1-line
646
smallest-index-with-equal-value
0.712
ye15
Easy
28,508
2,057
find the minimum and maximum number of nodes between critical points
class Solution: def nodesBetweenCriticalPoints(self, head: Optional[ListNode]) -> List[int]: min_res = math.inf min_point = max_point = last_point = None prev_val = head.val head = head.next i = 1 while head.next: if ((head.next.val < head.val and prev_val < head.val) or (head.next.val > head.val and prev_val > head.val)): if min_point is None: min_point = i else: max_point = i if last_point: min_res = min(min_res, i - last_point) last_point = i prev_val = head.val i += 1 head = head.next if min_res == math.inf: min_res = -1 max_res = max_point - min_point if max_point else -1 return [min_res, max_res]
https://leetcode.com/problems/find-the-minimum-and-maximum-number-of-nodes-between-critical-points/discuss/1551353/Python-O(1)-memory-O(n)-time-beats-100.00
1
A critical point in a linked list is defined as either a local maxima or a local minima. A node is a local maxima if the current node has a value strictly greater than the previous node and the next node. A node is a local minima if the current node has a value strictly smaller than the previous node and the next node. Note that a node can only be a local maxima/minima if there exists both a previous node and a next node. Given a linked list head, return an array of length 2 containing [minDistance, maxDistance] where minDistance is the minimum distance between any two distinct critical points and maxDistance is the maximum distance between any two distinct critical points. If there are fewer than two critical points, return [-1, -1]. Example 1: Input: head = [3,1] Output: [-1,-1] Explanation: There are no critical points in [3,1]. Example 2: Input: head = [5,3,1,2,5,1,2] Output: [1,3] Explanation: There are three critical points: - [5,3,1,2,5,1,2]: The third node is a local minima because 1 is less than 3 and 2. - [5,3,1,2,5,1,2]: The fifth node is a local maxima because 5 is greater than 2 and 1. - [5,3,1,2,5,1,2]: The sixth node is a local minima because 1 is less than 5 and 2. The minimum distance is between the fifth and the sixth node. minDistance = 6 - 5 = 1. The maximum distance is between the third and the sixth node. maxDistance = 6 - 3 = 3. Example 3: Input: head = [1,3,2,2,3,2,2,2,7] Output: [3,3] Explanation: There are two critical points: - [1,3,2,2,3,2,2,2,7]: The second node is a local maxima because 3 is greater than 1 and 2. - [1,3,2,2,3,2,2,2,7]: The fifth node is a local maxima because 3 is greater than 2 and 2. Both the minimum and maximum distances are between the second and the fifth node. Thus, minDistance and maxDistance is 5 - 2 = 3. Note that the last node is not considered a local maxima because it does not have a next node. Constraints: The number of nodes in the list is in the range [2, 105]. 1 <= Node.val <= 105
Python O(1) memory, O(n) time beats 100.00%
125
find-the-minimum-and-maximum-number-of-nodes-between-critical-points
0.57
dereky4
Medium
28,534
2,058
minimum operations to convert number
class Solution: def minimumOperations(self, nums: List[int], start: int, goal: int) -> int: ans = 0 seen = {start} queue = deque([start]) while queue: for _ in range(len(queue)): val = queue.popleft() if val == goal: return ans if 0 <= val <= 1000: for x in nums: for op in (add, sub, xor): if op(val, x) not in seen: seen.add(op(val, x)) queue.append(op(val, x)) ans += 1 return -1
https://leetcode.com/problems/minimum-operations-to-convert-number/discuss/1550007/Python3-bfs
17
You are given a 0-indexed integer array nums containing distinct numbers, an integer start, and an integer goal. There is an integer x that is initially set to start, and you want to perform operations on x such that it is converted to goal. You can perform the following operation repeatedly on the number x: If 0 <= x <= 1000, then for any index i in the array (0 <= i < nums.length), you can set x to any of the following: x + nums[i] x - nums[i] x ^ nums[i] (bitwise-XOR) Note that you can use each nums[i] any number of times in any order. Operations that set x to be out of the range 0 <= x <= 1000 are valid, but no more operations can be done afterward. Return the minimum number of operations needed to convert x = start into goal, and -1 if it is not possible. Example 1: Input: nums = [2,4,12], start = 2, goal = 12 Output: 2 Explanation: We can go from 2 β†’ 14 β†’ 12 with the following 2 operations. - 2 + 12 = 14 - 14 - 2 = 12 Example 2: Input: nums = [3,5,7], start = 0, goal = -4 Output: 2 Explanation: We can go from 0 β†’ 3 β†’ -4 with the following 2 operations. - 0 + 3 = 3 - 3 - 7 = -4 Note that the last operation sets x out of the range 0 <= x <= 1000, which is valid. Example 3: Input: nums = [2,8,16], start = 0, goal = 1 Output: -1 Explanation: There is no way to convert 0 into 1. Constraints: 1 <= nums.length <= 1000 -109 <= nums[i], goal <= 109 0 <= start <= 1000 start != goal All the integers in nums are distinct.
[Python3] bfs
1,200
minimum-operations-to-convert-number
0.473
ye15
Medium
28,540
2,059
check if an original string exists given two encoded strings
class Solution: def possiblyEquals(self, s1: str, s2: str) -> bool: def gg(s): """Return possible length""" ans = [int(s)] if len(s) == 2: if s[1] != '0': ans.append(int(s[0]) + int(s[1])) return ans elif len(s) == 3: if s[1] != '0': ans.append(int(s[:1]) + int(s[1:])) if s[2] != '0': ans.append(int(s[:2]) + int(s[2:])) if s[1] != '0' and s[2] != '0': ans.append(int(s[0]) + int(s[1]) + int(s[2])) return ans @cache def fn(i, j, diff): """Return True if s1[i:] matches s2[j:] with given differences.""" if i == len(s1) and j == len(s2): return diff == 0 if i < len(s1) and s1[i].isdigit(): ii = i while ii < len(s1) and s1[ii].isdigit(): ii += 1 for x in gg(s1[i:ii]): if fn(ii, j, diff-x): return True elif j < len(s2) and s2[j].isdigit(): jj = j while jj < len(s2) and s2[jj].isdigit(): jj += 1 for x in gg(s2[j:jj]): if fn(i, jj, diff+x): return True elif diff == 0: if i == len(s1) or j == len(s2) or s1[i] != s2[j]: return False return fn(i+1, j+1, 0) elif diff > 0: if i == len(s1): return False return fn(i+1, j, diff-1) else: if j == len(s2): return False return fn(i, j+1, diff+1) return fn(0, 0, 0)
https://leetcode.com/problems/check-if-an-original-string-exists-given-two-encoded-strings/discuss/1550012/Python3-dp
82
An original string, consisting of lowercase English letters, can be encoded by the following steps: Arbitrarily split it into a sequence of some number of non-empty substrings. Arbitrarily choose some elements (possibly none) of the sequence, and replace each with its length (as a numeric string). Concatenate the sequence as the encoded string. For example, one way to encode an original string "abcdefghijklmnop" might be: Split it as a sequence: ["ab", "cdefghijklmn", "o", "p"]. Choose the second and third elements to be replaced by their lengths, respectively. The sequence becomes ["ab", "12", "1", "p"]. Concatenate the elements of the sequence to get the encoded string: "ab121p". Given two encoded strings s1 and s2, consisting of lowercase English letters and digits 1-9 (inclusive), return true if there exists an original string that could be encoded as both s1 and s2. Otherwise, return false. Note: The test cases are generated such that the number of consecutive digits in s1 and s2 does not exceed 3. Example 1: Input: s1 = "internationalization", s2 = "i18n" Output: true Explanation: It is possible that "internationalization" was the original string. - "internationalization" -> Split: ["internationalization"] -> Do not replace any element -> Concatenate: "internationalization", which is s1. - "internationalization" -> Split: ["i", "nternationalizatio", "n"] -> Replace: ["i", "18", "n"] -> Concatenate: "i18n", which is s2 Example 2: Input: s1 = "l123e", s2 = "44" Output: true Explanation: It is possible that "leetcode" was the original string. - "leetcode" -> Split: ["l", "e", "et", "cod", "e"] -> Replace: ["l", "1", "2", "3", "e"] -> Concatenate: "l123e", which is s1. - "leetcode" -> Split: ["leet", "code"] -> Replace: ["4", "4"] -> Concatenate: "44", which is s2. Example 3: Input: s1 = "a5b", s2 = "c5b" Output: false Explanation: It is impossible. - The original string encoded as s1 must start with the letter 'a'. - The original string encoded as s2 must start with the letter 'c'. Constraints: 1 <= s1.length, s2.length <= 40 s1 and s2 consist of digits 1-9 (inclusive), and lowercase English letters only. The number of consecutive digits in s1 and s2 does not exceed 3.
[Python3] dp
6,200
check-if-an-original-string-exists-given-two-encoded-strings
0.407
ye15
Hard
28,550
2,060
count vowel substrings of a string
class Solution: def countVowelSubstrings(self, word: str) -> int: ans = 0 freq = defaultdict(int) for i, x in enumerate(word): if x in "aeiou": if not i or word[i-1] not in "aeiou": jj = j = i # set anchor freq.clear() freq[x] += 1 while len(freq) == 5 and all(freq.values()): freq[word[j]] -= 1 j += 1 ans += j - jj return ans
https://leetcode.com/problems/count-vowel-substrings-of-a-string/discuss/1563707/Python3-sliding-window-O(N)
16
A substring is a contiguous (non-empty) sequence of characters within a string. A vowel substring is a substring that only consists of vowels ('a', 'e', 'i', 'o', and 'u') and has all five vowels present in it. Given a string word, return the number of vowel substrings in word. Example 1: Input: word = "aeiouu" Output: 2 Explanation: The vowel substrings of word are as follows (underlined): - "aeiouu" - "aeiouu" Example 2: Input: word = "unicornarihan" Output: 0 Explanation: Not all 5 vowels are present, so there are no vowel substrings. Example 3: Input: word = "cuaieuouac" Output: 7 Explanation: The vowel substrings of word are as follows (underlined): - "cuaieuouac" - "cuaieuouac" - "cuaieuouac" - "cuaieuouac" - "cuaieuouac" - "cuaieuouac" - "cuaieuouac" Constraints: 1 <= word.length <= 100 word consists of lowercase English letters only.
[Python3] sliding window O(N)
1,900
count-vowel-substrings-of-a-string
0.659
ye15
Easy
28,552
2,062
vowels of all substrings
class Solution: def countVowels(self, word: str) -> int: count = 0 sz = len(word) for pos in range(sz): if word[pos] in 'aeiou': count += (sz - pos) * (pos + 1) return count
https://leetcode.com/problems/vowels-of-all-substrings/discuss/1564075/Detailed-explanation-of-why-(len-pos)-*-(pos-%2B-1)-works
77
Given a string word, return the sum of the number of vowels ('a', 'e', 'i', 'o', and 'u') in every substring of word. A substring is a contiguous (non-empty) sequence of characters within a string. Note: Due to the large constraints, the answer may not fit in a signed 32-bit integer. Please be careful during the calculations. Example 1: Input: word = "aba" Output: 6 Explanation: All possible substrings are: "a", "ab", "aba", "b", "ba", and "a". - "b" has 0 vowels in it - "a", "ab", "ba", and "a" have 1 vowel each - "aba" has 2 vowels in it Hence, the total sum of vowels = 0 + 1 + 1 + 1 + 1 + 2 = 6. Example 2: Input: word = "abc" Output: 3 Explanation: All possible substrings are: "a", "ab", "abc", "b", "bc", and "c". - "a", "ab", and "abc" have 1 vowel each - "b", "bc", and "c" have 0 vowels each Hence, the total sum of vowels = 1 + 1 + 1 + 0 + 0 + 0 = 3. Example 3: Input: word = "ltcd" Output: 0 Explanation: There are no vowels in any substring of "ltcd". Constraints: 1 <= word.length <= 105 word consists of lowercase English letters.
Detailed explanation of why (len - pos) * (pos + 1) works
2,000
vowels-of-all-substrings
0.551
bitmasker
Medium
28,564
2,063
minimized maximum of products distributed to any store
class Solution: def minimizedMaximum(self, n: int, quantities: List[int]) -> int: lo, hi = 1, max(quantities) while lo < hi: mid = lo + hi >> 1 if sum(ceil(qty/mid) for qty in quantities) <= n: hi = mid else: lo = mid + 1 return lo
https://leetcode.com/problems/minimized-maximum-of-products-distributed-to-any-store/discuss/1563731/Python3-binary-search
9
You are given an integer n indicating there are n specialty retail stores. There are m product types of varying amounts, which are given as a 0-indexed integer array quantities, where quantities[i] represents the number of products of the ith product type. You need to distribute all products to the retail stores following these rules: A store can only be given at most one product type but can be given any amount of it. After distribution, each store will have been given some number of products (possibly 0). Let x represent the maximum number of products given to any store. You want x to be as small as possible, i.e., you want to minimize the maximum number of products that are given to any store. Return the minimum possible x. Example 1: Input: n = 6, quantities = [11,6] Output: 3 Explanation: One optimal way is: - The 11 products of type 0 are distributed to the first four stores in these amounts: 2, 3, 3, 3 - The 6 products of type 1 are distributed to the other two stores in these amounts: 3, 3 The maximum number of products given to any store is max(2, 3, 3, 3, 3, 3) = 3. Example 2: Input: n = 7, quantities = [15,10,10] Output: 5 Explanation: One optimal way is: - The 15 products of type 0 are distributed to the first three stores in these amounts: 5, 5, 5 - The 10 products of type 1 are distributed to the next two stores in these amounts: 5, 5 - The 10 products of type 2 are distributed to the last two stores in these amounts: 5, 5 The maximum number of products given to any store is max(5, 5, 5, 5, 5, 5, 5) = 5. Example 3: Input: n = 1, quantities = [100000] Output: 100000 Explanation: The only optimal way is: - The 100000 products of type 0 are distributed to the only store. The maximum number of products given to any store is max(100000) = 100000. Constraints: m == quantities.length 1 <= m <= n <= 105 1 <= quantities[i] <= 105
[Python3] binary search
296
minimized-maximum-of-products-distributed-to-any-store
0.5
ye15
Medium
28,577
2,064
maximum path quality of a graph
class Solution: def maximalPathQuality(self, values: List[int], edges: List[List[int]], maxTime: int) -> int: ans = 0 graph = collections.defaultdict(dict) for u, v, t in edges: graph[u][v] = t graph[v][u] = t def dfs(curr, visited, score, cost): if curr == 0: nonlocal ans ans = max(ans, score) for nxt, time in graph[curr].items(): if time <= cost: dfs(nxt, visited|set([nxt]), score+values[nxt]*(nxt not in visited), cost-time) dfs(0, set([0]), values[0], maxTime) return ans
https://leetcode.com/problems/maximum-path-quality-of-a-graph/discuss/1564102/Python-DFS-and-BFS-solution
2
There is an undirected graph with n nodes numbered from 0 to n - 1 (inclusive). You are given a 0-indexed integer array values where values[i] is the value of the ith node. You are also given a 0-indexed 2D integer array edges, where each edges[j] = [uj, vj, timej] indicates that there is an undirected edge between the nodes uj and vj, and it takes timej seconds to travel between the two nodes. Finally, you are given an integer maxTime. A valid path in the graph is any path that starts at node 0, ends at node 0, and takes at most maxTime seconds to complete. You may visit the same node multiple times. The quality of a valid path is the sum of the values of the unique nodes visited in the path (each node's value is added at most once to the sum). Return the maximum quality of a valid path. Note: There are at most four edges connected to each node. Example 1: Input: values = [0,32,10,43], edges = [[0,1,10],[1,2,15],[0,3,10]], maxTime = 49 Output: 75 Explanation: One possible path is 0 -> 1 -> 0 -> 3 -> 0. The total time taken is 10 + 10 + 10 + 10 = 40 <= 49. The nodes visited are 0, 1, and 3, giving a maximal path quality of 0 + 32 + 43 = 75. Example 2: Input: values = [5,10,15,20], edges = [[0,1,10],[1,2,10],[0,3,10]], maxTime = 30 Output: 25 Explanation: One possible path is 0 -> 3 -> 0. The total time taken is 10 + 10 = 20 <= 30. The nodes visited are 0 and 3, giving a maximal path quality of 5 + 20 = 25. Example 3: Input: values = [1,2,3,4], edges = [[0,1,10],[1,2,11],[2,3,12],[1,3,13]], maxTime = 50 Output: 7 Explanation: One possible path is 0 -> 1 -> 3 -> 1 -> 0. The total time taken is 10 + 13 + 13 + 10 = 46 <= 50. The nodes visited are 0, 1, and 3, giving a maximal path quality of 1 + 2 + 4 = 7. Constraints: n == values.length 1 <= n <= 1000 0 <= values[i] <= 108 0 <= edges.length <= 2000 edges[j].length == 3 0 <= uj < vj <= n - 1 10 <= timej, maxTime <= 100 All the pairs [uj, vj] are unique. There are at most four edges connected to each node. The graph may not be connected.
[Python] DFS and BFS solution
424
maximum-path-quality-of-a-graph
0.576
nightybear
Hard
28,583
2,065
check whether two strings are almost equivalent
class Solution: def checkAlmostEquivalent(self, word1: str, word2: str) -> bool: freq = [0]*26 for x in word1: freq[ord(x)-97] += 1 for x in word2: freq[ord(x)-97] -= 1 return all(abs(x) <= 3 for x in freq)
https://leetcode.com/problems/check-whether-two-strings-are-almost-equivalent/discuss/1576339/Python3-freq-table
2
Two strings word1 and word2 are considered almost equivalent if the differences between the frequencies of each letter from 'a' to 'z' between word1 and word2 is at most 3. Given two strings word1 and word2, each of length n, return true if word1 and word2 are almost equivalent, or false otherwise. The frequency of a letter x is the number of times it occurs in the string. Example 1: Input: word1 = "aaaa", word2 = "bccb" Output: false Explanation: There are 4 'a's in "aaaa" but 0 'a's in "bccb". The difference is 4, which is more than the allowed 3. Example 2: Input: word1 = "abcdeef", word2 = "abaaacc" Output: true Explanation: The differences between the frequencies of each letter in word1 and word2 are at most 3: - 'a' appears 1 time in word1 and 4 times in word2. The difference is 3. - 'b' appears 1 time in word1 and 1 time in word2. The difference is 0. - 'c' appears 1 time in word1 and 2 times in word2. The difference is 1. - 'd' appears 1 time in word1 and 0 times in word2. The difference is 1. - 'e' appears 2 times in word1 and 0 times in word2. The difference is 2. - 'f' appears 1 time in word1 and 0 times in word2. The difference is 1. Example 3: Input: word1 = "cccddabba", word2 = "babababab" Output: true Explanation: The differences between the frequencies of each letter in word1 and word2 are at most 3: - 'a' appears 2 times in word1 and 4 times in word2. The difference is 2. - 'b' appears 2 times in word1 and 5 times in word2. The difference is 3. - 'c' appears 3 times in word1 and 0 times in word2. The difference is 3. - 'd' appears 2 times in word1 and 0 times in word2. The difference is 2. Constraints: n == word1.length == word2.length 1 <= n <= 100 word1 and word2 consist only of lowercase English letters.
[Python3] freq table
140
check-whether-two-strings-are-almost-equivalent
0.646
ye15
Easy
28,589
2,068
most beautiful item for each query
class Solution: def maximumBeauty(self, items: List[List[int]], queries: List[int]) -> List[int]: items.sort() dic = dict() res = [] gmax = 0 for p,b in items: gmax = max(b,gmax) dic[p] = gmax keys = sorted(dic.keys()) for q in queries: ind = bisect.bisect_left(keys,q) if ind<len(keys) and keys[ind]==q: res.append(dic[q]) elif ind==0: res.append(0) else: res.append(dic[keys[ind-1]]) return res
https://leetcode.com/problems/most-beautiful-item-for-each-query/discuss/1596922/Well-Explained-oror-99-faster-oror-Mainly-for-Beginners
4
You are given a 2D integer array items where items[i] = [pricei, beautyi] denotes the price and beauty of an item respectively. You are also given a 0-indexed integer array queries. For each queries[j], you want to determine the maximum beauty of an item whose price is less than or equal to queries[j]. If no such item exists, then the answer to this query is 0. Return an array answer of the same length as queries where answer[j] is the answer to the jth query. Example 1: Input: items = [[1,2],[3,2],[2,4],[5,6],[3,5]], queries = [1,2,3,4,5,6] Output: [2,4,5,5,6,6] Explanation: - For queries[0]=1, [1,2] is the only item which has price <= 1. Hence, the answer for this query is 2. - For queries[1]=2, the items which can be considered are [1,2] and [2,4]. The maximum beauty among them is 4. - For queries[2]=3 and queries[3]=4, the items which can be considered are [1,2], [3,2], [2,4], and [3,5]. The maximum beauty among them is 5. - For queries[4]=5 and queries[5]=6, all items can be considered. Hence, the answer for them is the maximum beauty of all items, i.e., 6. Example 2: Input: items = [[1,2],[1,2],[1,3],[1,4]], queries = [1] Output: [4] Explanation: The price of every item is equal to 1, so we choose the item with the maximum beauty 4. Note that multiple items can have the same price and/or beauty. Example 3: Input: items = [[10,1000]], queries = [5] Output: [0] Explanation: No item has a price less than or equal to 5, so no item can be chosen. Hence, the answer to the query is 0. Constraints: 1 <= items.length, queries.length <= 105 items[i].length == 2 1 <= pricei, beautyi, queries[j] <= 109
πŸ“ŒπŸ“Œ Well-Explained || 99% faster || Mainly for Beginners 🐍
124
most-beautiful-item-for-each-query
0.498
abhi9Rai
Medium
28,612
2,070
maximum number of tasks you can assign
class Solution: def maxTaskAssign(self, tasks: List[int], workers: List[int], pills: int, strength: int) -> int: # workers sorted in reverse order, tasks sorted in normal order def can_assign(n): task_i = 0 task_temp = deque() n_pills = pills for i in range(n-1,-1,-1): while task_i < n and tasks[task_i] <= workers[i]+strength: task_temp.append(tasks[task_i]) task_i += 1 if len(task_temp) == 0: return False if workers[i] >= task_temp[0]: task_temp.popleft() elif n_pills > 0: task_temp.pop() n_pills -= 1 else: return False return True tasks.sort() workers.sort(reverse = True) l = 0 r = min(len(tasks), len(workers)) res = -1 while l <= r: m = (l+r)//2 if can_assign(m): res = m l = m+1 else: r = m-1 return res
https://leetcode.com/problems/maximum-number-of-tasks-you-can-assign/discuss/1588356/python-binary-search-%2B-greedy-with-deque-O(nlogn)
9
You have n tasks and m workers. Each task has a strength requirement stored in a 0-indexed integer array tasks, with the ith task requiring tasks[i] strength to complete. The strength of each worker is stored in a 0-indexed integer array workers, with the jth worker having workers[j] strength. Each worker can only be assigned to a single task and must have a strength greater than or equal to the task's strength requirement (i.e., workers[j] >= tasks[i]). Additionally, you have pills magical pills that will increase a worker's strength by strength. You can decide which workers receive the magical pills, however, you may only give each worker at most one magical pill. Given the 0-indexed integer arrays tasks and workers and the integers pills and strength, return the maximum number of tasks that can be completed. Example 1: Input: tasks = [3,2,1], workers = [0,3,3], pills = 1, strength = 1 Output: 3 Explanation: We can assign the magical pill and tasks as follows: - Give the magical pill to worker 0. - Assign worker 0 to task 2 (0 + 1 >= 1) - Assign worker 1 to task 1 (3 >= 2) - Assign worker 2 to task 0 (3 >= 3) Example 2: Input: tasks = [5,4], workers = [0,0,0], pills = 1, strength = 5 Output: 1 Explanation: We can assign the magical pill and tasks as follows: - Give the magical pill to worker 0. - Assign worker 0 to task 0 (0 + 5 >= 5) Example 3: Input: tasks = [10,15,30], workers = [0,10,10,10,10], pills = 3, strength = 10 Output: 2 Explanation: We can assign the magical pills and tasks as follows: - Give the magical pill to worker 0 and worker 1. - Assign worker 0 to task 0 (0 + 10 >= 10) - Assign worker 1 to task 1 (10 + 10 >= 15) The last pill is not given because it will not make any worker strong enough for the last task. Constraints: n == tasks.length m == workers.length 1 <= n, m <= 5 * 104 0 <= pills <= m 0 <= tasks[i], workers[j], strength <= 109
[python] binary search + greedy with deque O(nlogn)
403
maximum-number-of-tasks-you-can-assign
0.346
hkwu6013
Hard
28,622
2,071
time needed to buy tickets
class Solution: def timeRequiredToBuy(self, tickets: list[int], k: int) -> int: secs = 0 i = 0 while tickets[k] != 0: if tickets[i] != 0: # if it is zero that means we dont have to count it anymore tickets[i] -= 1 # decrease the value by 1 everytime secs += 1 # increase secs by 1 i = (i + 1) % len(tickets) # since after getting to the end of the array we have to return to the first value so we use the mod operator return secs
https://leetcode.com/problems/time-needed-to-buy-tickets/discuss/1577018/Python-or-BruteForce-and-O(N)
30
There are n people in a line queuing to buy tickets, where the 0th person is at the front of the line and the (n - 1)th person is at the back of the line. You are given a 0-indexed integer array tickets of length n where the number of tickets that the ith person would like to buy is tickets[i]. Each person takes exactly 1 second to buy a ticket. A person can only buy 1 ticket at a time and has to go back to the end of the line (which happens instantaneously) in order to buy more tickets. If a person does not have any tickets left to buy, the person will leave the line. Return the time taken for the person at position k (0-indexed) to finish buying tickets. Example 1: Input: tickets = [2,3,2], k = 2 Output: 6 Explanation: - In the first pass, everyone in the line buys a ticket and the line becomes [1, 2, 1]. - In the second pass, everyone in the line buys a ticket and the line becomes [0, 1, 0]. The person at position 2 has successfully bought 2 tickets and it took 3 + 3 = 6 seconds. Example 2: Input: tickets = [5,1,1,1], k = 0 Output: 8 Explanation: - In the first pass, everyone in the line buys a ticket and the line becomes [4, 0, 0, 0]. - In the next 4 passes, only the person in position 0 is buying tickets. The person at position 0 has successfully bought 5 tickets and it took 4 + 1 + 1 + 1 + 1 = 8 seconds. Constraints: n == tickets.length 1 <= n <= 100 1 <= tickets[i] <= 100 0 <= k < n
[Python] | BruteForce and O(N)
1,600
time-needed-to-buy-tickets
0.62
GigaMoksh
Easy
28,625
2,073
reverse nodes in even length groups
class Solution: def reverseEvenLengthGroups(self, head: Optional[ListNode]) -> Optional[ListNode]: n, node = 0, head while node: n, node = n+1, node.next k, node = 0, head while n: k += 1 size = min(k, n) stack = [] if not size &amp; 1: temp = node for _ in range(size): stack.append(temp.val) temp = temp.next for _ in range(size): if stack: node.val = stack.pop() node = node.next n -= size return head
https://leetcode.com/problems/reverse-nodes-in-even-length-groups/discuss/1577058/Python3-using-stack
11
You are given the head of a linked list. The nodes in the linked list are sequentially assigned to non-empty groups whose lengths form the sequence of the natural numbers (1, 2, 3, 4, ...). The length of a group is the number of nodes assigned to it. In other words, The 1st node is assigned to the first group. The 2nd and the 3rd nodes are assigned to the second group. The 4th, 5th, and 6th nodes are assigned to the third group, and so on. Note that the length of the last group may be less than or equal to 1 + the length of the second to last group. Reverse the nodes in each group with an even length, and return the head of the modified linked list. Example 1: Input: head = [5,2,6,3,9,1,7,3,8,4] Output: [5,6,2,3,9,1,4,8,3,7] Explanation: - The length of the first group is 1, which is odd, hence no reversal occurs. - The length of the second group is 2, which is even, hence the nodes are reversed. - The length of the third group is 3, which is odd, hence no reversal occurs. - The length of the last group is 4, which is even, hence the nodes are reversed. Example 2: Input: head = [1,1,0,6] Output: [1,0,1,6] Explanation: - The length of the first group is 1. No reversal occurs. - The length of the second group is 2. The nodes are reversed. - The length of the last group is 1. No reversal occurs. Example 3: Input: head = [1,1,0,6,5] Output: [1,0,1,5,6] Explanation: - The length of the first group is 1. No reversal occurs. - The length of the second group is 2. The nodes are reversed. - The length of the last group is 2. The nodes are reversed. Constraints: The number of nodes in the list is in the range [1, 105]. 0 <= Node.val <= 105
[Python3] using stack
445
reverse-nodes-in-even-length-groups
0.521
ye15
Medium
28,656
2,074
decode the slanted ciphertext
class Solution: def decodeCiphertext(self, encodedText: str, rows: int) -> str: cols, res = len(encodedText) // rows, "" for i in range(cols): for j in range(i, len(encodedText), cols + 1): res += encodedText[j] return res.rstrip()
https://leetcode.com/problems/decode-the-slanted-ciphertext/discuss/1576914/Jump-Columns-%2B-1
57
A string originalText is encoded using a slanted transposition cipher to a string encodedText with the help of a matrix having a fixed number of rows rows. originalText is placed first in a top-left to bottom-right manner. The blue cells are filled first, followed by the red cells, then the yellow cells, and so on, until we reach the end of originalText. The arrow indicates the order in which the cells are filled. All empty cells are filled with ' '. The number of columns is chosen such that the rightmost column will not be empty after filling in originalText. encodedText is then formed by appending all characters of the matrix in a row-wise fashion. The characters in the blue cells are appended first to encodedText, then the red cells, and so on, and finally the yellow cells. The arrow indicates the order in which the cells are accessed. For example, if originalText = "cipher" and rows = 3, then we encode it in the following manner: The blue arrows depict how originalText is placed in the matrix, and the red arrows denote the order in which encodedText is formed. In the above example, encodedText = "ch ie pr". Given the encoded string encodedText and number of rows rows, return the original string originalText. Note: originalText does not have any trailing spaces ' '. The test cases are generated such that there is only one possible originalText. Example 1: Input: encodedText = "ch ie pr", rows = 3 Output: "cipher" Explanation: This is the same example described in the problem description. Example 2: Input: encodedText = "iveo eed l te olc", rows = 4 Output: "i love leetcode" Explanation: The figure above denotes the matrix that was used to encode originalText. The blue arrows show how we can find originalText from encodedText. Example 3: Input: encodedText = "coding", rows = 1 Output: "coding" Explanation: Since there is only 1 row, both originalText and encodedText are the same. Constraints: 0 <= encodedText.length <= 106 encodedText consists of lowercase English letters and ' ' only. encodedText is a valid encoding of some originalText that does not have trailing spaces. 1 <= rows <= 1000 The testcases are generated such that there is only one possible originalText.
Jump Columns + 1
2,000
decode-the-slanted-ciphertext
0.502
votrubac
Medium
28,663
2,075
process restricted friend requests
class Solution: def friendRequests(self, n: int, restrictions: List[List[int]], requests: List[List[int]]) -> List[bool]: result = [False for _ in requests] connected_components = [{i} for i in range(n)] connected_comp_dict = {} for i in range(n): connected_comp_dict[i] = i banned_by_comps = [set() for i in range(n)] for res in restrictions: banned_by_comps[res[0]].add(res[1]) banned_by_comps[res[1]].add(res[0]) for i,r in enumerate(requests): n1, n2 = r[0], r[1] c1, c2 = connected_comp_dict[n1], connected_comp_dict[n2] if c1 == c2: result[i] = True else: if not (connected_components[c1].intersection(banned_by_comps[c2]) or connected_components[c2].intersection(banned_by_comps[c1])): connected_components[c1].update(connected_components[c2]) banned_by_comps[c1].update(banned_by_comps[c2]) for node in connected_components[c2]: connected_comp_dict[node] = c1 result[i] = True return result
https://leetcode.com/problems/process-restricted-friend-requests/discuss/1577153/Python-272-ms36-MB-Maintain-connected-components-of-the-graph
2
You are given an integer n indicating the number of people in a network. Each person is labeled from 0 to n - 1. You are also given a 0-indexed 2D integer array restrictions, where restrictions[i] = [xi, yi] means that person xi and person yi cannot become friends, either directly or indirectly through other people. Initially, no one is friends with each other. You are given a list of friend requests as a 0-indexed 2D integer array requests, where requests[j] = [uj, vj] is a friend request between person uj and person vj. A friend request is successful if uj and vj can be friends. Each friend request is processed in the given order (i.e., requests[j] occurs before requests[j + 1]), and upon a successful request, uj and vj become direct friends for all future friend requests. Return a boolean array result, where each result[j] is true if the jth friend request is successful or false if it is not. Note: If uj and vj are already direct friends, the request is still successful. Example 1: Input: n = 3, restrictions = [[0,1]], requests = [[0,2],[2,1]] Output: [true,false] Explanation: Request 0: Person 0 and person 2 can be friends, so they become direct friends. Request 1: Person 2 and person 1 cannot be friends since person 0 and person 1 would be indirect friends (1--2--0). Example 2: Input: n = 3, restrictions = [[0,1]], requests = [[1,2],[0,2]] Output: [true,false] Explanation: Request 0: Person 1 and person 2 can be friends, so they become direct friends. Request 1: Person 0 and person 2 cannot be friends since person 0 and person 1 would be indirect friends (0--2--1). Example 3: Input: n = 5, restrictions = [[0,1],[1,2],[2,3]], requests = [[0,4],[1,2],[3,1],[3,4]] Output: [true,false,true,false] Explanation: Request 0: Person 0 and person 4 can be friends, so they become direct friends. Request 1: Person 1 and person 2 cannot be friends since they are directly restricted. Request 2: Person 3 and person 1 can be friends, so they become direct friends. Request 3: Person 3 and person 4 cannot be friends since person 0 and person 1 would be indirect friends (0--4--3--1). Constraints: 2 <= n <= 1000 0 <= restrictions.length <= 1000 restrictions[i].length == 2 0 <= xi, yi <= n - 1 xi != yi 1 <= requests.length <= 1000 requests[j].length == 2 0 <= uj, vj <= n - 1 uj != vj
[Python] [272 ms,36 MB] Maintain connected components of the graph
189
process-restricted-friend-requests
0.532
LonelyQuantum
Hard
28,677
2,076
two furthest houses with different colors
class Solution: def maxDistance(self, colors: List[int]) -> int: ans = 0 for i, x in enumerate(colors): if x != colors[0]: ans = max(ans, i) if x != colors[-1]: ans = max(ans, len(colors)-1-i) return ans
https://leetcode.com/problems/two-furthest-houses-with-different-colors/discuss/1589119/Python3-one-of-end-points-will-be-used
25
There are n houses evenly lined up on the street, and each house is beautifully painted. You are given a 0-indexed integer array colors of length n, where colors[i] represents the color of the ith house. Return the maximum distance between two houses with different colors. The distance between the ith and jth houses is abs(i - j), where abs(x) is the absolute value of x. Example 1: Input: colors = [1,1,1,6,1,1,1] Output: 3 Explanation: In the above image, color 1 is blue, and color 6 is red. The furthest two houses with different colors are house 0 and house 3. House 0 has color 1, and house 3 has color 6. The distance between them is abs(0 - 3) = 3. Note that houses 3 and 6 can also produce the optimal answer. Example 2: Input: colors = [1,8,3,8,3] Output: 4 Explanation: In the above image, color 1 is blue, color 8 is yellow, and color 3 is green. The furthest two houses with different colors are house 0 and house 4. House 0 has color 1, and house 4 has color 3. The distance between them is abs(0 - 4) = 4. Example 3: Input: colors = [0,1] Output: 1 Explanation: The furthest two houses with different colors are house 0 and house 1. House 0 has color 0, and house 1 has color 1. The distance between them is abs(0 - 1) = 1. Constraints: n == colors.length 2 <= n <= 100 0 <= colors[i] <= 100 Test data are generated such that at least two houses have different colors.
[Python3] one of end points will be used
887
two-furthest-houses-with-different-colors
0.671
ye15
Easy
28,678
2,078
watering plants
class Solution: def wateringPlants(self, plants: List[int], capacity: int) -> int: ans = 0 can = capacity for i, x in enumerate(plants): if can < x: ans += 2*i can = capacity ans += 1 can -= x return ans
https://leetcode.com/problems/watering-plants/discuss/1589030/Python3-simulation
19
You want to water n plants in your garden with a watering can. The plants are arranged in a row and are labeled from 0 to n - 1 from left to right where the ith plant is located at x = i. There is a river at x = -1 that you can refill your watering can at. Each plant needs a specific amount of water. You will water the plants in the following way: Water the plants in order from left to right. After watering the current plant, if you do not have enough water to completely water the next plant, return to the river to fully refill the watering can. You cannot refill the watering can early. You are initially at the river (i.e., x = -1). It takes one step to move one unit on the x-axis. Given a 0-indexed integer array plants of n integers, where plants[i] is the amount of water the ith plant needs, and an integer capacity representing the watering can capacity, return the number of steps needed to water all the plants. Example 1: Input: plants = [2,2,3,3], capacity = 5 Output: 14 Explanation: Start at the river with a full watering can: - Walk to plant 0 (1 step) and water it. Watering can has 3 units of water. - Walk to plant 1 (1 step) and water it. Watering can has 1 unit of water. - Since you cannot completely water plant 2, walk back to the river to refill (2 steps). - Walk to plant 2 (3 steps) and water it. Watering can has 2 units of water. - Since you cannot completely water plant 3, walk back to the river to refill (3 steps). - Walk to plant 3 (4 steps) and water it. Steps needed = 1 + 1 + 2 + 3 + 3 + 4 = 14. Example 2: Input: plants = [1,1,1,4,2,3], capacity = 4 Output: 30 Explanation: Start at the river with a full watering can: - Water plants 0, 1, and 2 (3 steps). Return to river (3 steps). - Water plant 3 (4 steps). Return to river (4 steps). - Water plant 4 (5 steps). Return to river (5 steps). - Water plant 5 (6 steps). Steps needed = 3 + 3 + 4 + 4 + 5 + 5 + 6 = 30. Example 3: Input: plants = [7,7,7,7,7,7,7], capacity = 8 Output: 49 Explanation: You have to refill before watering each plant. Steps needed = 1 + 1 + 2 + 2 + 3 + 3 + 4 + 4 + 5 + 5 + 6 + 6 + 7 = 49. Constraints: n == plants.length 1 <= n <= 1000 1 <= plants[i] <= 106 max(plants[i]) <= capacity <= 109
[Python3] simulation
1,000
watering-plants
0.8
ye15
Medium
28,701
2,079
sum of k mirror numbers
class Solution: def kMirror(self, k: int, n: int) -> int: def fn(x): """Return next k-symmetric number.""" n = len(x)//2 for i in range(n, len(x)): if int(x[i])+1 < k: x[i] = x[~i] = str(int(x[i])+1) for ii in range(n, i): x[ii] = x[~ii] = '0' return x return ["1"] + ["0"]*(len(x)-1) + ["1"] x = ["0"] ans = 0 for _ in range(n): while True: x = fn(x) val = int("".join(x), k) if str(val)[::-1] == str(val): break ans += val return ans
https://leetcode.com/problems/sum-of-k-mirror-numbers/discuss/1589048/Python3-enumerate-k-symmetric-numbers
41
A k-mirror number is a positive integer without leading zeros that reads the same both forward and backward in base-10 as well as in base-k. For example, 9 is a 2-mirror number. The representation of 9 in base-10 and base-2 are 9 and 1001 respectively, which read the same both forward and backward. On the contrary, 4 is not a 2-mirror number. The representation of 4 in base-2 is 100, which does not read the same both forward and backward. Given the base k and the number n, return the sum of the n smallest k-mirror numbers. Example 1: Input: k = 2, n = 5 Output: 25 Explanation: The 5 smallest 2-mirror numbers and their representations in base-2 are listed as follows: base-10 base-2 1 1 3 11 5 101 7 111 9 1001 Their sum = 1 + 3 + 5 + 7 + 9 = 25. Example 2: Input: k = 3, n = 7 Output: 499 Explanation: The 7 smallest 3-mirror numbers are and their representations in base-3 are listed as follows: base-10 base-3 1 1 2 2 4 11 8 22 121 11111 151 12121 212 21212 Their sum = 1 + 2 + 4 + 8 + 121 + 151 + 212 = 499. Example 3: Input: k = 7, n = 17 Output: 20379000 Explanation: The 17 smallest 7-mirror numbers are: 1, 2, 3, 4, 5, 6, 8, 121, 171, 242, 292, 16561, 65656, 2137312, 4602064, 6597956, 6958596 Constraints: 2 <= k <= 9 1 <= n <= 30
[Python3] enumerate k-symmetric numbers
2,700
sum-of-k-mirror-numbers
0.421
ye15
Hard
28,741
2,081
count common words with one occurrence
class Solution: def countWords(self, words1: List[str], words2: List[str]) -> int: freq1, freq2 = Counter(words1), Counter(words2) return len({w for w, v in freq1.items() if v == 1} &amp; {w for w, v in freq2.items() if v == 1})
https://leetcode.com/problems/count-common-words-with-one-occurrence/discuss/1598944/Python3-2-line-freq-table
10
Given two string arrays words1 and words2, return the number of strings that appear exactly once in each of the two arrays. Example 1: Input: words1 = ["leetcode","is","amazing","as","is"], words2 = ["amazing","leetcode","is"] Output: 2 Explanation: - "leetcode" appears exactly once in each of the two arrays. We count this string. - "amazing" appears exactly once in each of the two arrays. We count this string. - "is" appears in each of the two arrays, but there are 2 occurrences of it in words1. We do not count this string. - "as" appears once in words1, but does not appear in words2. We do not count this string. Thus, there are 2 strings that appear exactly once in each of the two arrays. Example 2: Input: words1 = ["b","bb","bbb"], words2 = ["a","aa","aaa"] Output: 0 Explanation: There are no strings that appear in each of the two arrays. Example 3: Input: words1 = ["a","ab"], words2 = ["a","a","a","ab"] Output: 1 Explanation: The only string that appears exactly once in each of the two arrays is "ab". Constraints: 1 <= words1.length, words2.length <= 1000 1 <= words1[i].length, words2[j].length <= 30 words1[i] and words2[j] consists only of lowercase English letters.
[Python3] 2-line freq table
1,200
count-common-words-with-one-occurrence
0.697
ye15
Easy
28,746
2,085
minimum number of food buckets to feed the hamsters
class Solution: def minimumBuckets(self, street: str) -> int: street = list(street) ans = 0 for i, ch in enumerate(street): if ch == 'H' and (i == 0 or street[i-1] != '#'): if i+1 < len(street) and street[i+1] == '.': street[i+1] = '#' elif i and street[i-1] == '.': street[i-1] = '#' else: return -1 ans += 1 return ans
https://leetcode.com/problems/minimum-number-of-food-buckets-to-feed-the-hamsters/discuss/1598954/Python3-greedy
10
You are given a 0-indexed string hamsters where hamsters[i] is either: 'H' indicating that there is a hamster at index i, or '.' indicating that index i is empty. You will add some number of food buckets at the empty indices in order to feed the hamsters. A hamster can be fed if there is at least one food bucket to its left or to its right. More formally, a hamster at index i can be fed if you place a food bucket at index i - 1 and/or at index i + 1. Return the minimum number of food buckets you should place at empty indices to feed all the hamsters or -1 if it is impossible to feed all of them. Example 1: Input: hamsters = "H..H" Output: 2 Explanation: We place two food buckets at indices 1 and 2. It can be shown that if we place only one food bucket, one of the hamsters will not be fed. Example 2: Input: hamsters = ".H.H." Output: 1 Explanation: We place one food bucket at index 2. Example 3: Input: hamsters = ".HHH." Output: -1 Explanation: If we place a food bucket at every empty index as shown, the hamster at index 2 will not be able to eat. Constraints: 1 <= hamsters.length <= 105 hamsters[i] is either'H' or '.'.
[Python3] greedy
541
minimum-number-of-food-buckets-to-feed-the-hamsters
0.451
ye15
Medium
28,788
2,086
minimum cost homecoming of a robot in a grid
class Solution: def minCost(self, startPos: List[int], homePos: List[int], rowCosts: List[int], colCosts: List[int]) -> int: src_x,src_y = startPos[0],startPos[1] end_x,end_y = homePos[0], homePos[1] if src_x < end_x: rc = sum(rowCosts[src_x+1:end_x+1]) elif src_x > end_x: rc = sum(rowCosts[end_x:src_x]) else: rc=0 if src_y < end_y: cc = sum(colCosts[src_y+1:end_y+1]) elif src_y > end_y: cc = sum(colCosts[end_y:src_y]) else: cc=0 return cc+rc
https://leetcode.com/problems/minimum-cost-homecoming-of-a-robot-in-a-grid/discuss/1598918/Greedy-Approach-oror-Well-Coded-and-Explained-oror-95-faster
3
There is an m x n grid, where (0, 0) is the top-left cell and (m - 1, n - 1) is the bottom-right cell. You are given an integer array startPos where startPos = [startrow, startcol] indicates that initially, a robot is at the cell (startrow, startcol). You are also given an integer array homePos where homePos = [homerow, homecol] indicates that its home is at the cell (homerow, homecol). The robot needs to go to its home. It can move one cell in four directions: left, right, up, or down, and it can not move outside the boundary. Every move incurs some cost. You are further given two 0-indexed integer arrays: rowCosts of length m and colCosts of length n. If the robot moves up or down into a cell whose row is r, then this move costs rowCosts[r]. If the robot moves left or right into a cell whose column is c, then this move costs colCosts[c]. Return the minimum total cost for this robot to return home. Example 1: Input: startPos = [1, 0], homePos = [2, 3], rowCosts = [5, 4, 3], colCosts = [8, 2, 6, 7] Output: 18 Explanation: One optimal path is that: Starting from (1, 0) -> It goes down to (2, 0). This move costs rowCosts[2] = 3. -> It goes right to (2, 1). This move costs colCosts[1] = 2. -> It goes right to (2, 2). This move costs colCosts[2] = 6. -> It goes right to (2, 3). This move costs colCosts[3] = 7. The total cost is 3 + 2 + 6 + 7 = 18 Example 2: Input: startPos = [0, 0], homePos = [0, 0], rowCosts = [5], colCosts = [26] Output: 0 Explanation: The robot is already at its home. Since no moves occur, the total cost is 0. Constraints: m == rowCosts.length n == colCosts.length 1 <= m, n <= 105 0 <= rowCosts[r], colCosts[c] <= 104 startPos.length == 2 homePos.length == 2 0 <= startrow, homerow < m 0 <= startcol, homecol < n
πŸ“ŒπŸ“Œ Greedy Approach || Well-Coded and Explained || 95% faster 🐍
276
minimum-cost-homecoming-of-a-robot-in-a-grid
0.513
abhi9Rai
Medium
28,797
2,087
count fertile pyramids in a land
class Solution: def countPyramids(self, grid: List[List[int]]) -> int: m, n = len(grid), len(grid[0]) vals = [[inf]*n for _ in range(m)] for i in range(m): for j in range(n): if grid[i][j] == 0: vals[i][j] = 0 elif j == 0: vals[i][j] = 1 else: vals[i][j] = min(vals[i][j], 1 + vals[i][j-1]) if grid[i][~j] == 0: vals[i][~j] = 0 elif j == 0: vals[i][~j] = 1 else: vals[i][~j] = min(vals[i][~j], 1 + vals[i][~j+1]) def fn(vals): """Return count of pyramid in given grid.""" ans = 0 for j in range(n): width = 0 for i in range(m): if vals[i][j]: width = min(width+1, vals[i][j]) else: width = 0 ans += max(0, width-1) return ans return fn(vals) + fn(vals[::-1])
https://leetcode.com/problems/count-fertile-pyramids-in-a-land/discuss/1598873/Python3-just-count
5
A farmer has a rectangular grid of land with m rows and n columns that can be divided into unit cells. Each cell is either fertile (represented by a 1) or barren (represented by a 0). All cells outside the grid are considered barren. A pyramidal plot of land can be defined as a set of cells with the following criteria: The number of cells in the set has to be greater than 1 and all cells must be fertile. The apex of a pyramid is the topmost cell of the pyramid. The height of a pyramid is the number of rows it covers. Let (r, c) be the apex of the pyramid, and its height be h. Then, the plot comprises of cells (i, j) where r <= i <= r + h - 1 and c - (i - r) <= j <= c + (i - r). An inverse pyramidal plot of land can be defined as a set of cells with similar criteria: The number of cells in the set has to be greater than 1 and all cells must be fertile. The apex of an inverse pyramid is the bottommost cell of the inverse pyramid. The height of an inverse pyramid is the number of rows it covers. Let (r, c) be the apex of the pyramid, and its height be h. Then, the plot comprises of cells (i, j) where r - h + 1 <= i <= r and c - (r - i) <= j <= c + (r - i). Some examples of valid and invalid pyramidal (and inverse pyramidal) plots are shown below. Black cells indicate fertile cells. Given a 0-indexed m x n binary matrix grid representing the farmland, return the total number of pyramidal and inverse pyramidal plots that can be found in grid. Example 1: Input: grid = [[0,1,1,0],[1,1,1,1]] Output: 2 Explanation: The 2 possible pyramidal plots are shown in blue and red respectively. There are no inverse pyramidal plots in this grid. Hence total number of pyramidal and inverse pyramidal plots is 2 + 0 = 2. Example 2: Input: grid = [[1,1,1],[1,1,1]] Output: 2 Explanation: The pyramidal plot is shown in blue, and the inverse pyramidal plot is shown in red. Hence the total number of plots is 1 + 1 = 2. Example 3: Input: grid = [[1,1,1,1,0],[1,1,1,1,1],[1,1,1,1,1],[0,1,0,0,1]] Output: 13 Explanation: There are 7 pyramidal plots, 3 of which are shown in the 2nd and 3rd figures. There are 6 inverse pyramidal plots, 2 of which are shown in the last figure. The total number of plots is 7 + 6 = 13. Constraints: m == grid.length n == grid[i].length 1 <= m, n <= 1000 1 <= m * n <= 105 grid[i][j] is either 0 or 1.
[Python3] just count
415
count-fertile-pyramids-in-a-land
0.635
ye15
Hard
28,802
2,088
find target indices after sorting array
class Solution: def targetIndices(self, nums, target): ans = [] for i,num in enumerate(sorted(nums)): if num == target: ans.append(i) return ans
https://leetcode.com/problems/find-target-indices-after-sorting-array/discuss/2024498/Python-Solution-%2B-One-Line!
10
You are given a 0-indexed integer array nums and a target element target. A target index is an index i such that nums[i] == target. Return a list of the target indices of nums after sorting nums in non-decreasing order. If there are no target indices, return an empty list. The returned list must be sorted in increasing order. Example 1: Input: nums = [1,2,5,2,3], target = 2 Output: [1,2] Explanation: After sorting, nums is [1,2,2,3,5]. The indices where nums[i] == 2 are 1 and 2. Example 2: Input: nums = [1,2,5,2,3], target = 3 Output: [3] Explanation: After sorting, nums is [1,2,2,3,5]. The index where nums[i] == 3 is 3. Example 3: Input: nums = [1,2,5,2,3], target = 5 Output: [4] Explanation: After sorting, nums is [1,2,2,3,5]. The index where nums[i] == 5 is 4. Constraints: 1 <= nums.length <= 100 1 <= nums[i], target <= 100
Python - Solution + One-Line!
377
find-target-indices-after-sorting-array
0.766
domthedeveloper
Easy
28,813
2,089
k radius subarray averages
class Solution: def getAverages(self, nums: List[int], k: int) -> List[int]: res = [-1]*len(nums) left, curWindowSum, diameter = 0, 0, 2*k+1 for right in range(len(nums)): curWindowSum += nums[right] if (right-left+1 >= diameter): res[left+k] = curWindowSum//diameter curWindowSum -= nums[left] left += 1 return res
https://leetcode.com/problems/k-radius-subarray-averages/discuss/1599973/Python-3-or-Sliding-Window-or-Illustration-with-picture
48
You are given a 0-indexed array nums of n integers, and an integer k. The k-radius average for a subarray of nums centered at some index i with the radius k is the average of all elements in nums between the indices i - k and i + k (inclusive). If there are less than k elements before or after the index i, then the k-radius average is -1. Build and return an array avgs of length n where avgs[i] is the k-radius average for the subarray centered at index i. The average of x elements is the sum of the x elements divided by x, using integer division. The integer division truncates toward zero, which means losing its fractional part. For example, the average of four elements 2, 3, 1, and 5 is (2 + 3 + 1 + 5) / 4 = 11 / 4 = 2.75, which truncates to 2. Example 1: Input: nums = [7,4,3,9,1,8,5,2,6], k = 3 Output: [-1,-1,-1,5,4,4,-1,-1,-1] Explanation: - avg[0], avg[1], and avg[2] are -1 because there are less than k elements before each index. - The sum of the subarray centered at index 3 with radius 3 is: 7 + 4 + 3 + 9 + 1 + 8 + 5 = 37. Using integer division, avg[3] = 37 / 7 = 5. - For the subarray centered at index 4, avg[4] = (4 + 3 + 9 + 1 + 8 + 5 + 2) / 7 = 4. - For the subarray centered at index 5, avg[5] = (3 + 9 + 1 + 8 + 5 + 2 + 6) / 7 = 4. - avg[6], avg[7], and avg[8] are -1 because there are less than k elements after each index. Example 2: Input: nums = [100000], k = 0 Output: [100000] Explanation: - The sum of the subarray centered at index 0 with radius 0 is: 100000. avg[0] = 100000 / 1 = 100000. Example 3: Input: nums = [8], k = 100000 Output: [-1] Explanation: - avg[0] is -1 because there are less than k elements before and after index 0. Constraints: n == nums.length 1 <= n <= 105 0 <= nums[i], k <= 105
Python 3 | Sliding Window | Illustration with picture
1,300
k-radius-subarray-averages
0.426
ndus
Medium
28,861
2,090
removing minimum and maximum from array
class Solution: def minimumDeletions(self, nums: List[int]) -> int: imin = nums.index(min(nums)) imax = nums.index(max(nums)) return min(max(imin, imax)+1, len(nums)-min(imin, imax), len(nums)+1+min(imin, imax)-max(imin, imax))
https://leetcode.com/problems/removing-minimum-and-maximum-from-array/discuss/1599862/Python3-3-candidates
5
You are given a 0-indexed array of distinct integers nums. There is an element in nums that has the lowest value and an element that has the highest value. We call them the minimum and maximum respectively. Your goal is to remove both these elements from the array. A deletion is defined as either removing an element from the front of the array or removing an element from the back of the array. Return the minimum number of deletions it would take to remove both the minimum and maximum element from the array. Example 1: Input: nums = [2,10,7,5,4,1,8,6] Output: 5 Explanation: The minimum element in the array is nums[5], which is 1. The maximum element in the array is nums[1], which is 10. We can remove both the minimum and maximum by removing 2 elements from the front and 3 elements from the back. This results in 2 + 3 = 5 deletions, which is the minimum number possible. Example 2: Input: nums = [0,-4,19,1,8,-2,-3,5] Output: 3 Explanation: The minimum element in the array is nums[1], which is -4. The maximum element in the array is nums[2], which is 19. We can remove both the minimum and maximum by removing 3 elements from the front. This results in only 3 deletions, which is the minimum number possible. Example 3: Input: nums = [101] Output: 1 Explanation: There is only one element in the array, which makes it both the minimum and maximum element. We can remove it with 1 deletion. Constraints: 1 <= nums.length <= 105 -105 <= nums[i] <= 105 The integers in nums are distinct.
[Python3] 3 candidates
226
removing-minimum-and-maximum-from-array
0.566
ye15
Medium
28,879
2,091
find all people with secret
class Solution: def findAllPeople(self, n: int, meetings: List[List[int]], firstPerson: int) -> List[int]: can = {0, firstPerson} for _, grp in groupby(sorted(meetings, key=lambda x: x[2]), key=lambda x: x[2]): queue = set() graph = defaultdict(list) for x, y, _ in grp: graph[x].append(y) graph[y].append(x) if x in can: queue.add(x) if y in can: queue.add(y) queue = deque(queue) while queue: x = queue.popleft() for y in graph[x]: if y not in can: can.add(y) queue.append(y) return can
https://leetcode.com/problems/find-all-people-with-secret/discuss/1599870/Python3-BFS-or-DFS-by-group
29
You are given an integer n indicating there are n people numbered from 0 to n - 1. You are also given a 0-indexed 2D integer array meetings where meetings[i] = [xi, yi, timei] indicates that person xi and person yi have a meeting at timei. A person may attend multiple meetings at the same time. Finally, you are given an integer firstPerson. Person 0 has a secret and initially shares the secret with a person firstPerson at time 0. This secret is then shared every time a meeting takes place with a person that has the secret. More formally, for every meeting, if a person xi has the secret at timei, then they will share the secret with person yi, and vice versa. The secrets are shared instantaneously. That is, a person may receive the secret and share it with people in other meetings within the same time frame. Return a list of all the people that have the secret after all the meetings have taken place. You may return the answer in any order. Example 1: Input: n = 6, meetings = [[1,2,5],[2,3,8],[1,5,10]], firstPerson = 1 Output: [0,1,2,3,5] Explanation: At time 0, person 0 shares the secret with person 1. At time 5, person 1 shares the secret with person 2. At time 8, person 2 shares the secret with person 3. At time 10, person 1 shares the secret with person 5. Thus, people 0, 1, 2, 3, and 5 know the secret after all the meetings. Example 2: Input: n = 4, meetings = [[3,1,3],[1,2,2],[0,3,3]], firstPerson = 3 Output: [0,1,3] Explanation: At time 0, person 0 shares the secret with person 3. At time 2, neither person 1 nor person 2 know the secret. At time 3, person 3 shares the secret with person 0 and person 1. Thus, people 0, 1, and 3 know the secret after all the meetings. Example 3: Input: n = 5, meetings = [[3,4,2],[1,2,1],[2,3,1]], firstPerson = 1 Output: [0,1,2,3,4] Explanation: At time 0, person 0 shares the secret with person 1. At time 1, person 1 shares the secret with person 2, and person 2 shares the secret with person 3. Note that person 2 can share the secret at the same time as receiving it. At time 2, person 3 shares the secret with person 4. Thus, people 0, 1, 2, 3, and 4 know the secret after all the meetings. Constraints: 2 <= n <= 105 1 <= meetings.length <= 105 meetings[i].length == 3 0 <= xi, yi <= n - 1 xi != yi 1 <= timei <= 105 1 <= firstPerson <= n - 1
[Python3] BFS or DFS by group
3,100
find-all-people-with-secret
0.342
ye15
Hard
28,900
2,092
finding 3 digit even numbers
class Solution: def findEvenNumbers(self, digits: List[int]) -> List[int]: ans = set() for x, y, z in permutations(digits, 3): if x != 0 and z &amp; 1 == 0: ans.add(100*x + 10*y + z) return sorted(ans)
https://leetcode.com/problems/finding-3-digit-even-numbers/discuss/1611987/Python3-brute-force
29
You are given an integer array digits, where each element is a digit. The array may contain duplicates. You need to find all the unique integers that follow the given requirements: The integer consists of the concatenation of three elements from digits in any arbitrary order. The integer does not have leading zeros. The integer is even. For example, if the given digits were [1, 2, 3], integers 132 and 312 follow the requirements. Return a sorted array of the unique integers. Example 1: Input: digits = [2,1,3,0] Output: [102,120,130,132,210,230,302,310,312,320] Explanation: All the possible integers that follow the requirements are in the output array. Notice that there are no odd integers or integers with leading zeros. Example 2: Input: digits = [2,2,8,8,2] Output: [222,228,282,288,822,828,882] Explanation: The same digit can be used as many times as it appears in digits. In this example, the digit 8 is used twice each time in 288, 828, and 882. Example 3: Input: digits = [3,7,5] Output: [] Explanation: No even integers can be formed using the given digits. Constraints: 3 <= digits.length <= 100 0 <= digits[i] <= 9
[Python3] brute-force
1,900
finding-3-digit-even-numbers
0.574
ye15
Easy
28,911
2,094
delete the middle node of a linked list
class Solution: def deleteMiddle(self, head: Optional[ListNode]) -> Optional[ListNode]: slow,fast,prev=head,head,None while fast and fast.next: prev=slow slow=slow.next fast=fast.next.next if prev==None: return None prev.next=slow.next return head
https://leetcode.com/problems/delete-the-middle-node-of-a-linked-list/discuss/2700533/Fastest-python-solution-TC%3A-O(N)SC%3A-O(1)
12
You are given the head of a linked list. Delete the middle node, and return the head of the modified linked list. The middle node of a linked list of size n is the ⌊n / 2βŒ‹th node from the start using 0-based indexing, where ⌊xβŒ‹ denotes the largest integer less than or equal to x. For n = 1, 2, 3, 4, and 5, the middle nodes are 0, 1, 1, 2, and 2, respectively. Example 1: Input: head = [1,3,4,7,1,2,6] Output: [1,3,4,1,2,6] Explanation: The above figure represents the given linked list. The indices of the nodes are written below. Since n = 7, node 3 with value 7 is the middle node, which is marked in red. We return the new list after removing this node. Example 2: Input: head = [1,2,3,4] Output: [1,2,4] Explanation: The above figure represents the given linked list. For n = 4, node 2 with value 3 is the middle node, which is marked in red. Example 3: Input: head = [2,1] Output: [2] Explanation: The above figure represents the given linked list. For n = 2, node 1 with value 1 is the middle node, which is marked in red. Node 0 with value 2 is the only node remaining after removing node 1. Constraints: The number of nodes in the list is in the range [1, 105]. 1 <= Node.val <= 105
Fastest python solution TC: O(N),SC: O(1)
1,200
delete-the-middle-node-of-a-linked-list
0.605
shubham_1307
Medium
28,930
2,095
step by step directions from a binary tree node to another
class Solution: def getDirections(self, root: Optional[TreeNode], startValue: int, destValue: int) -> str: def lca(node): """Return lowest common ancestor of start and dest nodes.""" if not node or node.val in (startValue , destValue): return node left, right = lca(node.left), lca(node.right) return node if left and right else left or right root = lca(root) # only this sub-tree matters ps = pd = "" stack = [(root, "")] while stack: node, path = stack.pop() if node.val == startValue: ps = path if node.val == destValue: pd = path if node.left: stack.append((node.left, path + "L")) if node.right: stack.append((node.right, path + "R")) return "U"*len(ps) + pd
https://leetcode.com/problems/step-by-step-directions-from-a-binary-tree-node-to-another/discuss/1612179/Python3-lca
108
You are given the root of a binary tree with n nodes. Each node is uniquely assigned a value from 1 to n. You are also given an integer startValue representing the value of the start node s, and a different integer destValue representing the value of the destination node t. Find the shortest path starting from node s and ending at node t. Generate step-by-step directions of such path as a string consisting of only the uppercase letters 'L', 'R', and 'U'. Each letter indicates a specific direction: 'L' means to go from a node to its left child node. 'R' means to go from a node to its right child node. 'U' means to go from a node to its parent node. Return the step-by-step directions of the shortest path from node s to node t. Example 1: Input: root = [5,1,2,3,null,6,4], startValue = 3, destValue = 6 Output: "UURL" Explanation: The shortest path is: 3 β†’ 1 β†’ 5 β†’ 2 β†’ 6. Example 2: Input: root = [2,1], startValue = 2, destValue = 1 Output: "L" Explanation: The shortest path is: 2 β†’ 1. Constraints: The number of nodes in the tree is n. 2 <= n <= 105 1 <= Node.val <= n All the values in the tree are unique. 1 <= startValue, destValue <= n startValue != destValue
[Python3] lca
8,100
step-by-step-directions-from-a-binary-tree-node-to-another
0.488
ye15
Medium
28,951
2,096
valid arrangement of pairs
class Solution: def validArrangement(self, pairs: List[List[int]]) -> List[List[int]]: graph = defaultdict(list) degree = defaultdict(int) # net out degree for x, y in pairs: graph[x].append(y) degree[x] += 1 degree[y] -= 1 for k in degree: if degree[k] == 1: x = k break ans = [] def fn(x): """Return Eulerian path via dfs.""" while graph[x]: fn(graph[x].pop()) ans.append(x) fn(x) ans.reverse() return [[ans[i], ans[i+1]] for i in range(len(ans)-1)]
https://leetcode.com/problems/valid-arrangement-of-pairs/discuss/1612010/Python3-Hierholzer's-algo
32
You are given a 0-indexed 2D integer array pairs where pairs[i] = [starti, endi]. An arrangement of pairs is valid if for every index i where 1 <= i < pairs.length, we have endi-1 == starti. Return any valid arrangement of pairs. Note: The inputs will be generated such that there exists a valid arrangement of pairs. Example 1: Input: pairs = [[5,1],[4,5],[11,9],[9,4]] Output: [[11,9],[9,4],[4,5],[5,1]] Explanation: This is a valid arrangement since endi-1 always equals starti. end0 = 9 == 9 = start1 end1 = 4 == 4 = start2 end2 = 5 == 5 = start3 Example 2: Input: pairs = [[1,3],[3,2],[2,1]] Output: [[1,3],[3,2],[2,1]] Explanation: This is a valid arrangement since endi-1 always equals starti. end0 = 3 == 3 = start1 end1 = 2 == 2 = start2 The arrangements [[2,1],[1,3],[3,2]] and [[3,2],[2,1],[1,3]] are also valid. Example 3: Input: pairs = [[1,2],[1,3],[2,1]] Output: [[1,2],[2,1],[1,3]] Explanation: This is a valid arrangement since endi-1 always equals starti. end0 = 2 == 2 = start1 end1 = 1 == 1 = start2 Constraints: 1 <= pairs.length <= 105 pairs[i].length == 2 0 <= starti, endi <= 109 starti != endi No two pairs are exactly the same. There exists a valid arrangement of pairs.
[Python3] Hierholzer's algo
1,400
valid-arrangement-of-pairs
0.41
ye15
Hard
28,970
2,097
find subsequence of length k with the largest sum
class Solution: def maxSubsequence(self, nums: List[int], k: int) -> List[int]: tuple_heap = [] # Stores (value, index) as min heap for i, val in enumerate(nums): if len(tuple_heap) == k: heappushpop(tuple_heap, (val, i)) # To prevent size of heap growing larger than k else: heappush(tuple_heap, (val, i)) # heap now contains only the k largest elements with their indices as well. tuple_heap.sort(key=lambda x: x[1]) # To get the original order of values. That is why we sort it by index(x[1]) &amp; not value(x[0]) ans = [] for i in tuple_heap: ans.append(i[0]) return ans
https://leetcode.com/problems/find-subsequence-of-length-k-with-the-largest-sum/discuss/1705383/Python-Simple-Solution-or-100-Time
10
You are given an integer array nums and an integer k. You want to find a subsequence of nums of length k that has the largest sum. Return any such subsequence as an integer array of length k. A subsequence is an array that can be derived from another array by deleting some or no elements without changing the order of the remaining elements. Example 1: Input: nums = [2,1,3,3], k = 2 Output: [3,3] Explanation: The subsequence has the largest sum of 3 + 3 = 6. Example 2: Input: nums = [-1,-2,3,4], k = 3 Output: [-1,3,4] Explanation: The subsequence has the largest sum of -1 + 3 + 4 = 6. Example 3: Input: nums = [3,4,3,3], k = 2 Output: [3,4] Explanation: The subsequence has the largest sum of 3 + 4 = 7. Another possible subsequence is [4, 3]. Constraints: 1 <= nums.length <= 1000 -105 <= nums[i] <= 105 1 <= k <= nums.length
Python Simple Solution | 100% Time
806
find-subsequence-of-length-k-with-the-largest-sum
0.425
anCoderr
Easy
28,973
2,099
find good days to rob the bank
class Solution: def goodDaysToRobBank(self, security: List[int], time: int) -> List[int]: suffix = [0]*len(security) for i in range(len(security)-2, 0, -1): if security[i] <= security[i+1]: suffix[i] = suffix[i+1] + 1 ans = [] prefix = 0 for i in range(len(security)-time): if i and security[i-1] >= security[i]: prefix += 1 else: prefix = 0 if prefix >= time and suffix[i] >= time: ans.append(i) return ans
https://leetcode.com/problems/find-good-days-to-rob-the-bank/discuss/1623325/Python3-prefix-and-suffix
5
You and a gang of thieves are planning on robbing a bank. You are given a 0-indexed integer array security, where security[i] is the number of guards on duty on the ith day. The days are numbered starting from 0. You are also given an integer time. The ith day is a good day to rob the bank if: There are at least time days before and after the ith day, The number of guards at the bank for the time days before i are non-increasing, and The number of guards at the bank for the time days after i are non-decreasing. More formally, this means day i is a good day to rob the bank if and only if security[i - time] >= security[i - time + 1] >= ... >= security[i] <= ... <= security[i + time - 1] <= security[i + time]. Return a list of all days (0-indexed) that are good days to rob the bank. The order that the days are returned in does not matter. Example 1: Input: security = [5,3,3,3,5,6,2], time = 2 Output: [2,3] Explanation: On day 2, we have security[0] >= security[1] >= security[2] <= security[3] <= security[4]. On day 3, we have security[1] >= security[2] >= security[3] <= security[4] <= security[5]. No other days satisfy this condition, so days 2 and 3 are the only good days to rob the bank. Example 2: Input: security = [1,1,1,1,1], time = 0 Output: [0,1,2,3,4] Explanation: Since time equals 0, every day is a good day to rob the bank, so return every day. Example 3: Input: security = [1,2,3,4,5,6], time = 2 Output: [] Explanation: No day has 2 days before it that have a non-increasing number of guards. Thus, no day is a good day to rob the bank, so return an empty list. Constraints: 1 <= security.length <= 105 0 <= security[i], time <= 105
[Python3] prefix & suffix
243
find-good-days-to-rob-the-bank
0.492
ye15
Medium
29,003
2,100
detonate the maximum bombs
class Solution: def maximumDetonation(self, bombs: List[List[int]]) -> int: if len(bombs)==1: return 1 adlist={i:[] for i in range(len(bombs))} for i in range(len(bombs)): x1,y1,r1=bombs[i] for j in range(i+1,len(bombs)): x2,y2,r2=bombs[j] dist=((x2-x1)**2+(y2-y1)**2)**(1/2) if dist<=r1: adlist[i].append(j) if dist<=r2: adlist[j].append(i) def dfs(adlist,seen,start): seen.add(start) for i in adlist[start]: if i not in seen: dfs(adlist,seen,i) maxx=1 for v in adlist: seen=set() seen.add(v) dfs(adlist,seen,v) maxx=max(maxx,len(seen)) return maxx
https://leetcode.com/problems/detonate-the-maximum-bombs/discuss/1870271/Python-Solution-that-you-want-%3A
2
You are given a list of bombs. The range of a bomb is defined as the area where its effect can be felt. This area is in the shape of a circle with the center as the location of the bomb. The bombs are represented by a 0-indexed 2D integer array bombs where bombs[i] = [xi, yi, ri]. xi and yi denote the X-coordinate and Y-coordinate of the location of the ith bomb, whereas ri denotes the radius of its range. You may choose to detonate a single bomb. When a bomb is detonated, it will detonate all bombs that lie in its range. These bombs will further detonate the bombs that lie in their ranges. Given the list of bombs, return the maximum number of bombs that can be detonated if you are allowed to detonate only one bomb. Example 1: Input: bombs = [[2,1,3],[6,1,4]] Output: 2 Explanation: The above figure shows the positions and ranges of the 2 bombs. If we detonate the left bomb, the right bomb will not be affected. But if we detonate the right bomb, both bombs will be detonated. So the maximum bombs that can be detonated is max(1, 2) = 2. Example 2: Input: bombs = [[1,1,5],[10,10,5]] Output: 1 Explanation: Detonating either bomb will not detonate the other bomb, so the maximum number of bombs that can be detonated is 1. Example 3: Input: bombs = [[1,2,3],[2,3,1],[3,4,2],[4,5,3],[5,6,4]] Output: 5 Explanation: The best bomb to detonate is bomb 0 because: - Bomb 0 detonates bombs 1 and 2. The red circle denotes the range of bomb 0. - Bomb 2 detonates bomb 3. The blue circle denotes the range of bomb 2. - Bomb 3 detonates bomb 4. The green circle denotes the range of bomb 3. Thus all 5 bombs are detonated. Constraints: 1 <= bombs.length <= 100 bombs[i].length == 3 1 <= xi, yi, ri <= 105
Python Solution that you want :
201
detonate-the-maximum-bombs
0.413
goxy_coder
Medium
29,011
2,101
rings and rods
class Solution: def countPoints(self, r: str) -> int: ans = 0 for i in range(10): i = str(i) if 'R'+i in r and 'G'+i in r and 'B'+i in r: ans += 1 return ans
https://leetcode.com/problems/rings-and-rods/discuss/2044864/Python-simple-solution
7
There are n rings and each ring is either red, green, or blue. The rings are distributed across ten rods labeled from 0 to 9. You are given a string rings of length 2n that describes the n rings that are placed onto the rods. Every two characters in rings forms a color-position pair that is used to describe each ring where: The first character of the ith pair denotes the ith ring's color ('R', 'G', 'B'). The second character of the ith pair denotes the rod that the ith ring is placed on ('0' to '9'). For example, "R3G2B1" describes n == 3 rings: a red ring placed onto the rod labeled 3, a green ring placed onto the rod labeled 2, and a blue ring placed onto the rod labeled 1. Return the number of rods that have all three colors of rings on them. Example 1: Input: rings = "B0B6G0R6R0R6G9" Output: 1 Explanation: - The rod labeled 0 holds 3 rings with all colors: red, green, and blue. - The rod labeled 6 holds 3 rings, but it only has red and blue. - The rod labeled 9 holds only a green ring. Thus, the number of rods with all three colors is 1. Example 2: Input: rings = "B0R0G0R9R0B0G0" Output: 1 Explanation: - The rod labeled 0 holds 6 rings with all colors: red, green, and blue. - The rod labeled 9 holds only a red ring. Thus, the number of rods with all three colors is 1. Example 3: Input: rings = "G4" Output: 0 Explanation: Only one ring is given. Thus, no rods have all three colors. Constraints: rings.length == 2 * n 1 <= n <= 100 rings[i] where i is even is either 'R', 'G', or 'B' (0-indexed). rings[i] where i is odd is a digit from '0' to '9' (0-indexed).
Python simple solution
353
rings-and-rods
0.814
StikS32
Easy
29,018
2,103
sum of subarray ranges
class Solution: def subArrayRanges(self, nums: List[int]) -> int: def fn(op): """Return min sum (if given gt) or max sum (if given lt).""" ans = 0 stack = [] for i in range(len(nums) + 1): while stack and (i == len(nums) or op(nums[stack[-1]], nums[i])): mid = stack.pop() ii = stack[-1] if stack else -1 ans += nums[mid] * (i - mid) * (mid - ii) stack.append(i) return ans return fn(lt) - fn(gt)
https://leetcode.com/problems/sum-of-subarray-ranges/discuss/1624416/Python3-stack
17
You are given an integer array nums. The range of a subarray of nums is the difference between the largest and smallest element in the subarray. Return the sum of all subarray ranges of nums. A subarray is a contiguous non-empty sequence of elements within an array. Example 1: Input: nums = [1,2,3] Output: 4 Explanation: The 6 subarrays of nums are the following: [1], range = largest - smallest = 1 - 1 = 0 [2], range = 2 - 2 = 0 [3], range = 3 - 3 = 0 [1,2], range = 2 - 1 = 1 [2,3], range = 3 - 2 = 1 [1,2,3], range = 3 - 1 = 2 So the sum of all ranges is 0 + 0 + 0 + 1 + 1 + 2 = 4. Example 2: Input: nums = [1,3,3] Output: 4 Explanation: The 6 subarrays of nums are the following: [1], range = largest - smallest = 1 - 1 = 0 [3], range = 3 - 3 = 0 [3], range = 3 - 3 = 0 [1,3], range = 3 - 1 = 2 [3,3], range = 3 - 3 = 0 [1,3,3], range = 3 - 1 = 2 So the sum of all ranges is 0 + 0 + 0 + 2 + 0 + 2 = 4. Example 3: Input: nums = [4,-2,-3,4,1] Output: 59 Explanation: The sum of all subarray ranges of nums is 59. Constraints: 1 <= nums.length <= 1000 -109 <= nums[i] <= 109 Follow-up: Could you find a solution with O(n) time complexity?
[Python3] stack
3,900
sum-of-subarray-ranges
0.602
ye15
Medium
29,052
2,104
watering plants ii
class Solution: def minimumRefill(self, plants: List[int], capacityA: int, capacityB: int) -> int: ans = 0 lo, hi = 0, len(plants)-1 canA, canB = capacityA, capacityB while lo < hi: if canA < plants[lo]: ans += 1; canA = capacityA canA -= plants[lo] if canB < plants[hi]: ans += 1; canB = capacityB canB -= plants[hi] lo, hi = lo+1, hi-1 if lo == hi and max(canA, canB) < plants[lo]: ans += 1 return ans
https://leetcode.com/problems/watering-plants-ii/discuss/1624252/Python3-2-pointers
8
Alice and Bob want to water n plants in their garden. The plants are arranged in a row and are labeled from 0 to n - 1 from left to right where the ith plant is located at x = i. Each plant needs a specific amount of water. Alice and Bob have a watering can each, initially full. They water the plants in the following way: Alice waters the plants in order from left to right, starting from the 0th plant. Bob waters the plants in order from right to left, starting from the (n - 1)th plant. They begin watering the plants simultaneously. It takes the same amount of time to water each plant regardless of how much water it needs. Alice/Bob must water the plant if they have enough in their can to fully water it. Otherwise, they first refill their can (instantaneously) then water the plant. In case both Alice and Bob reach the same plant, the one with more water currently in his/her watering can should water this plant. If they have the same amount of water, then Alice should water this plant. Given a 0-indexed integer array plants of n integers, where plants[i] is the amount of water the ith plant needs, and two integers capacityA and capacityB representing the capacities of Alice's and Bob's watering cans respectively, return the number of times they have to refill to water all the plants. Example 1: Input: plants = [2,2,3,3], capacityA = 5, capacityB = 5 Output: 1 Explanation: - Initially, Alice and Bob have 5 units of water each in their watering cans. - Alice waters plant 0, Bob waters plant 3. - Alice and Bob now have 3 units and 2 units of water respectively. - Alice has enough water for plant 1, so she waters it. Bob does not have enough water for plant 2, so he refills his can then waters it. So, the total number of times they have to refill to water all the plants is 0 + 0 + 1 + 0 = 1. Example 2: Input: plants = [2,2,3,3], capacityA = 3, capacityB = 4 Output: 2 Explanation: - Initially, Alice and Bob have 3 units and 4 units of water in their watering cans respectively. - Alice waters plant 0, Bob waters plant 3. - Alice and Bob now have 1 unit of water each, and need to water plants 1 and 2 respectively. - Since neither of them have enough water for their current plants, they refill their cans and then water the plants. So, the total number of times they have to refill to water all the plants is 0 + 1 + 1 + 0 = 2. Example 3: Input: plants = [5], capacityA = 10, capacityB = 8 Output: 0 Explanation: - There is only one plant. - Alice's watering can has 10 units of water, whereas Bob's can has 8 units. Since Alice has more water in her can, she waters this plant. So, the total number of times they have to refill is 0. Constraints: n == plants.length 1 <= n <= 105 1 <= plants[i] <= 106 max(plants[i]) <= capacityA, capacityB <= 109
[Python3] 2 pointers
340
watering-plants-ii
0.501
ye15
Medium
29,071
2,105
maximum fruits harvested after at most k steps
class Solution: def maxTotalFruits(self, fruits: List[List[int]], startPos: int, k: int) -> int: fruitMap = defaultdict(int) for position, amount in fruits: fruitMap[position] = amount if k == 0: return fruitMap[startPos] totalLeft = 0 # max sum if we go k steps to the left totalRight = 0 # max sum if we go k steps to the right inBetween = 0 # max sum if we go x steps to the left &amp; k steps to the right (ensuring that we don't move more than k steps in total) dp = dict() for i in range(startPos,startPos-k-1, -1): totalLeft += fruitMap[i] dp[i] = totalLeft for i in range(startPos,startPos+k+1): totalRight += fruitMap[i] dp[i] = totalRight leftSteps = 1 rightSteps = k-2 while rightSteps > 0: currAmount = 0 # go right &amp; collect currAmount += dp[startPos-leftSteps] # go left &amp; collect currAmount += dp[startPos+rightSteps] inBetween = max(inBetween, currAmount-fruitMap[startPos]) leftSteps += 1 rightSteps -= 2 leftSteps = k-2 rightSteps = 1 while leftSteps > 0: currAmount = 0 # go right &amp; collect currAmount += dp[startPos-leftSteps] # go left &amp; collect currAmount += dp[startPos+rightSteps] inBetween = max(inBetween, currAmount-fruitMap[startPos]) leftSteps -= 2 rightSteps += 1 return max(totalLeft, totalRight, inBetween)
https://leetcode.com/problems/maximum-fruits-harvested-after-at-most-k-steps/discuss/1624294/Sliding-Window-or-Prefix-Suffix-Sum-or-Easy-to-understand
1
Fruits are available at some positions on an infinite x-axis. You are given a 2D integer array fruits where fruits[i] = [positioni, amounti] depicts amounti fruits at the position positioni. fruits is already sorted by positioni in ascending order, and each positioni is unique. You are also given an integer startPos and an integer k. Initially, you are at the position startPos. From any position, you can either walk to the left or right. It takes one step to move one unit on the x-axis, and you can walk at most k steps in total. For every position you reach, you harvest all the fruits at that position, and the fruits will disappear from that position. Return the maximum total number of fruits you can harvest. Example 1: Input: fruits = [[2,8],[6,3],[8,6]], startPos = 5, k = 4 Output: 9 Explanation: The optimal way is to: - Move right to position 6 and harvest 3 fruits - Move right to position 8 and harvest 6 fruits You moved 3 steps and harvested 3 + 6 = 9 fruits in total. Example 2: Input: fruits = [[0,9],[4,1],[5,7],[6,2],[7,4],[10,9]], startPos = 5, k = 4 Output: 14 Explanation: You can move at most k = 4 steps, so you cannot reach position 0 nor 10. The optimal way is to: - Harvest the 7 fruits at the starting position 5 - Move left to position 4 and harvest 1 fruit - Move right to position 6 and harvest 2 fruits - Move right to position 7 and harvest 4 fruits You moved 1 + 3 = 4 steps and harvested 7 + 1 + 2 + 4 = 14 fruits in total. Example 3: Input: fruits = [[0,3],[6,4],[8,5]], startPos = 3, k = 2 Output: 0 Explanation: You can move at most k = 2 steps and cannot reach any position with fruits. Constraints: 1 <= fruits.length <= 105 fruits[i].length == 2 0 <= startPos, positioni <= 2 * 105 positioni-1 < positioni for any i > 0 (0-indexed) 1 <= amounti <= 104 0 <= k <= 2 * 105
βœ… Sliding Window | Prefix Suffix Sum | Easy to understand
268
maximum-fruits-harvested-after-at-most-k-steps
0.351
CaptainX
Hard
29,081
2,106
find first palindromic string in the array
class Solution: def firstPalindrome(self, words): for word in words: if word == word[::-1]: return word return ""
https://leetcode.com/problems/find-first-palindromic-string-in-the-array/discuss/2022159/Python-Clean-and-Simple-%2B-One-Liner!
3
Given an array of strings words, return the first palindromic string in the array. If there is no such string, return an empty string "". A string is palindromic if it reads the same forward and backward. Example 1: Input: words = ["abc","car","ada","racecar","cool"] Output: "ada" Explanation: The first string that is palindromic is "ada". Note that "racecar" is also palindromic, but it is not the first. Example 2: Input: words = ["notapalindrome","racecar"] Output: "racecar" Explanation: The first and only string that is palindromic is "racecar". Example 3: Input: words = ["def","ghi"] Output: "" Explanation: There are no palindromic strings, so the empty string is returned. Constraints: 1 <= words.length <= 100 1 <= words[i].length <= 100 words[i] consists only of lowercase English letters.
Python - Clean and Simple + One-Liner!
128
find-first-palindromic-string-in-the-array
0.786
domthedeveloper
Easy
29,084
2,108
adding spaces to a string
class Solution: def addSpaces(self, s: str, spaces: List[int]) -> str: arr = [] prev = 0 for space in spaces: arr.append(s[prev:space]) prev = space arr.append(s[space:]) return " ".join(arr)
https://leetcode.com/problems/adding-spaces-to-a-string/discuss/1635075/Python-Split-and-Join-to-the-rescue.-From-TLE-to-Accepted-!-Straightforward
8
You are given a 0-indexed string s and a 0-indexed integer array spaces that describes the indices in the original string where spaces will be added. Each space should be inserted before the character at the given index. For example, given s = "EnjoyYourCoffee" and spaces = [5, 9], we place spaces before 'Y' and 'C', which are at indices 5 and 9 respectively. Thus, we obtain "Enjoy Your Coffee". Return the modified string after the spaces have been added. Example 1: Input: s = "LeetcodeHelpsMeLearn", spaces = [8,13,15] Output: "Leetcode Helps Me Learn" Explanation: The indices 8, 13, and 15 correspond to the underlined characters in "LeetcodeHelpsMeLearn". We then place spaces before those characters. Example 2: Input: s = "icodeinpython", spaces = [1,5,7,9] Output: "i code in py thon" Explanation: The indices 1, 5, 7, and 9 correspond to the underlined characters in "icodeinpython". We then place spaces before those characters. Example 3: Input: s = "spacing", spaces = [0,1,2,3,4,5,6] Output: " s p a c i n g" Explanation: We are also able to place spaces before the first character of the string. Constraints: 1 <= s.length <= 3 * 105 s consists only of lowercase and uppercase English letters. 1 <= spaces.length <= 3 * 105 0 <= spaces[i] <= s.length - 1 All the values of spaces are strictly increasing.
[Python] Split and Join to the rescue. From TLE to Accepted ! Straightforward
388
adding-spaces-to-a-string
0.563
mostlyAditya
Medium
29,132
2,109
number of smooth descent periods of a stock
class Solution: def getDescentPeriods(self, prices: List[int]) -> int: ans = 0 for i, x in enumerate(prices): if i == 0 or prices[i-1] != x + 1: cnt = 0 cnt += 1 ans += cnt return ans
https://leetcode.com/problems/number-of-smooth-descent-periods-of-a-stock/discuss/1635103/Python3-counting
6
You are given an integer array prices representing the daily price history of a stock, where prices[i] is the stock price on the ith day. A smooth descent period of a stock consists of one or more contiguous days such that the price on each day is lower than the price on the preceding day by exactly 1. The first day of the period is exempted from this rule. Return the number of smooth descent periods. Example 1: Input: prices = [3,2,1,4] Output: 7 Explanation: There are 7 smooth descent periods: [3], [2], [1], [4], [3,2], [2,1], and [3,2,1] Note that a period with one day is a smooth descent period by the definition. Example 2: Input: prices = [8,6,7,7] Output: 4 Explanation: There are 4 smooth descent periods: [8], [6], [7], and [7] Note that [8,6] is not a smooth descent period as 8 - 6 β‰  1. Example 3: Input: prices = [1] Output: 1 Explanation: There is 1 smooth descent period: [1] Constraints: 1 <= prices.length <= 105 1 <= prices[i] <= 105
[Python3] counting
279
number-of-smooth-descent-periods-of-a-stock
0.576
ye15
Medium
29,164
2,110
minimum operations to make the array k increasing
class Solution: def kIncreasing(self, arr: List[int], k: int) -> int: def fn(sub): """Return ops to make sub non-decreasing.""" vals = [] for x in sub: k = bisect_right(vals, x) if k == len(vals): vals.append(x) else: vals[k] = x return len(sub) - len(vals) return sum(fn(arr[i:len(arr):k]) for i in range(k))
https://leetcode.com/problems/minimum-operations-to-make-the-array-k-increasing/discuss/1635109/Python3-almost-LIS
2
You are given a 0-indexed array arr consisting of n positive integers, and a positive integer k. The array arr is called K-increasing if arr[i-k] <= arr[i] holds for every index i, where k <= i <= n-1. For example, arr = [4, 1, 5, 2, 6, 2] is K-increasing for k = 2 because: arr[0] <= arr[2] (4 <= 5) arr[1] <= arr[3] (1 <= 2) arr[2] <= arr[4] (5 <= 6) arr[3] <= arr[5] (2 <= 2) However, the same arr is not K-increasing for k = 1 (because arr[0] > arr[1]) or k = 3 (because arr[0] > arr[3]). In one operation, you can choose an index i and change arr[i] into any positive integer. Return the minimum number of operations required to make the array K-increasing for the given k. Example 1: Input: arr = [5,4,3,2,1], k = 1 Output: 4 Explanation: For k = 1, the resultant array has to be non-decreasing. Some of the K-increasing arrays that can be formed are [5,6,7,8,9], [1,1,1,1,1], [2,2,3,4,4]. All of them require 4 operations. It is suboptimal to change the array to, for example, [6,7,8,9,10] because it would take 5 operations. It can be shown that we cannot make the array K-increasing in less than 4 operations. Example 2: Input: arr = [4,1,5,2,6,2], k = 2 Output: 0 Explanation: This is the same example as the one in the problem description. Here, for every index i where 2 <= i <= 5, arr[i-2] <= arr[i]. Since the given array is already K-increasing, we do not need to perform any operations. Example 3: Input: arr = [4,1,5,2,6,2], k = 3 Output: 2 Explanation: Indices 3 and 5 are the only ones not satisfying arr[i-3] <= arr[i] for 3 <= i <= 5. One of the ways we can make the array K-increasing is by changing arr[3] to 4 and arr[5] to 5. The array will now be [4,1,5,4,6,5]. Note that there can be other ways to make the array K-increasing, but none of them require less than 2 operations. Constraints: 1 <= arr.length <= 105 1 <= arr[i], k <= arr.length
[Python3] almost LIS
177
minimum-operations-to-make-the-array-k-increasing
0.378
ye15
Hard
29,178
2,111
maximum number of words found in sentences
class Solution: def mostWordsFound(self, ss: List[str]) -> int: return max(s.count(" ") for s in ss) + 1
https://leetcode.com/problems/maximum-number-of-words-found-in-sentences/discuss/1646786/Count-Spaces
64
A sentence is a list of words that are separated by a single space with no leading or trailing spaces. You are given an array of strings sentences, where each sentences[i] represents a single sentence. Return the maximum number of words that appear in a single sentence. Example 1: Input: sentences = ["alice and bob love leetcode", "i think so too", "this is great thanks very much"] Output: 6 Explanation: - The first sentence, "alice and bob love leetcode", has 5 words in total. - The second sentence, "i think so too", has 4 words in total. - The third sentence, "this is great thanks very much", has 6 words in total. Thus, the maximum number of words in a single sentence comes from the third sentence, which has 6 words. Example 2: Input: sentences = ["please wait", "continue to fight", "continue to win"] Output: 3 Explanation: It is possible that multiple sentences contain the same number of words. In this example, the second and third sentences (underlined) have the same number of words. Constraints: 1 <= sentences.length <= 100 1 <= sentences[i].length <= 100 sentences[i] consists only of lowercase English letters and ' ' only. sentences[i] does not have leading or trailing spaces. All the words in sentences[i] are separated by a single space.
Count Spaces
8,100
maximum-number-of-words-found-in-sentences
0.88
votrubac
Easy
29,184
2,114
find all possible recipes from given supplies
class Solution: def findAllRecipes(self, recipes: List[str], ingredients: List[List[str]], supplies: List[str]) -> List[str]: graph, can_make, supplies = {recipe : [] for recipe in recipes}, {}, set(supplies) def dfs(recipe : str) -> bool: if recipe not in can_make: can_make[recipe] = False can_make[recipe] = all([dfs(ingr) for ingr in graph[recipe]]) return can_make[recipe] for i, recipe in enumerate(recipes): for ingr in ingredients[i]: if ingr not in supplies: graph[recipe].append(ingr if ingr in graph else recipe) return [recipe for recipe in recipes if dfs(recipe)]
https://leetcode.com/problems/find-all-possible-recipes-from-given-supplies/discuss/1646903/DFS
62
You have information about n different recipes. You are given a string array recipes and a 2D string array ingredients. The ith recipe has the name recipes[i], and you can create it if you have all the needed ingredients from ingredients[i]. Ingredients to a recipe may need to be created from other recipes, i.e., ingredients[i] may contain a string that is in recipes. You are also given a string array supplies containing all the ingredients that you initially have, and you have an infinite supply of all of them. Return a list of all the recipes that you can create. You may return the answer in any order. Note that two recipes may contain each other in their ingredients. Example 1: Input: recipes = ["bread"], ingredients = [["yeast","flour"]], supplies = ["yeast","flour","corn"] Output: ["bread"] Explanation: We can create "bread" since we have the ingredients "yeast" and "flour". Example 2: Input: recipes = ["bread","sandwich"], ingredients = [["yeast","flour"],["bread","meat"]], supplies = ["yeast","flour","meat"] Output: ["bread","sandwich"] Explanation: We can create "bread" since we have the ingredients "yeast" and "flour". We can create "sandwich" since we have the ingredient "meat" and can create the ingredient "bread". Example 3: Input: recipes = ["bread","sandwich","burger"], ingredients = [["yeast","flour"],["bread","meat"],["sandwich","meat","bread"]], supplies = ["yeast","flour","meat"] Output: ["bread","sandwich","burger"] Explanation: We can create "bread" since we have the ingredients "yeast" and "flour". We can create "sandwich" since we have the ingredient "meat" and can create the ingredient "bread". We can create "burger" since we have the ingredient "meat" and can create the ingredients "bread" and "sandwich". Constraints: n == recipes.length == ingredients.length 1 <= n <= 100 1 <= ingredients[i].length, supplies.length <= 100 1 <= recipes[i].length, ingredients[i][j].length, supplies[k].length <= 10 recipes[i], ingredients[i][j], and supplies[k] consist only of lowercase English letters. All the values of recipes and supplies combined are unique. Each ingredients[i] does not contain any duplicate values.
DFS
7,200
find-all-possible-recipes-from-given-supplies
0.485
votrubac
Medium
29,230
2,115
check if a parentheses string can be valid
class Solution: def canBeValid(self, s: str, locked: str) -> bool: def validate(s: str, locked: str, op: str) -> bool: bal, wild = 0, 0 for i in range(len(s)): if locked[i] == "1": bal += 1 if s[i] == op else -1 else: wild += 1 if wild + bal < 0: return False return bal <= wild return len(s) % 2 == 0 and validate(s, locked, '(') and validate(s[::-1], locked[::-1], ')')
https://leetcode.com/problems/check-if-a-parentheses-string-can-be-valid/discuss/1646594/Left-to-right-and-right-to-left
175
A parentheses string is a non-empty string consisting only of '(' and ')'. It is valid if any of the following conditions is true: It is (). It can be written as AB (A concatenated with B), where A and B are valid parentheses strings. It can be written as (A), where A is a valid parentheses string. You are given a parentheses string s and a string locked, both of length n. locked is a binary string consisting only of '0's and '1's. For each index i of locked, If locked[i] is '1', you cannot change s[i]. But if locked[i] is '0', you can change s[i] to either '(' or ')'. Return true if you can make s a valid parentheses string. Otherwise, return false. Example 1: Input: s = "))()))", locked = "010100" Output: true Explanation: locked[1] == '1' and locked[3] == '1', so we cannot change s[1] or s[3]. We change s[0] and s[4] to '(' while leaving s[2] and s[5] unchanged to make s valid. Example 2: Input: s = "()()", locked = "0000" Output: true Explanation: We do not need to make any changes because s is already valid. Example 3: Input: s = ")", locked = "0" Output: false Explanation: locked permits us to change s[0]. Changing s[0] to either '(' or ')' will not make s valid. Constraints: n == s.length == locked.length 1 <= n <= 105 s[i] is either '(' or ')'. locked[i] is either '0' or '1'.
Left-to-right and right-to-left
8,600
check-if-a-parentheses-string-can-be-valid
0.315
votrubac
Medium
29,255
2,116
abbreviating the product of a range
class Solution: def abbreviateProduct(self, left: int, right: int) -> str: ans = prefix = suffix = 1 trailing = 0 flag = False for x in range(left, right+1): if not flag: ans *= x while ans % 10 == 0: ans //= 10 if ans >= 1e10: flag = True prefix *= x suffix *= x while prefix >= 1e12: prefix //= 10 while suffix % 10 == 0: trailing += 1 suffix //= 10 if suffix >= 1e10: suffix %= 10_000_000_000 while prefix >= 100000: prefix //= 10 suffix %= 100000 if flag: return f"{prefix}...{suffix:>05}e{trailing}" return f"{ans}e{trailing}"
https://leetcode.com/problems/abbreviating-the-product-of-a-range/discuss/1646615/Python3-quasi-brute-force
10
You are given two positive integers left and right with left <= right. Calculate the product of all integers in the inclusive range [left, right]. Since the product may be very large, you will abbreviate it following these steps: Count all trailing zeros in the product and remove them. Let us denote this count as C. For example, there are 3 trailing zeros in 1000, and there are 0 trailing zeros in 546. Denote the remaining number of digits in the product as d. If d > 10, then express the product as <pre>...<suf> where <pre> denotes the first 5 digits of the product, and <suf> denotes the last 5 digits of the product after removing all trailing zeros. If d <= 10, we keep it unchanged. For example, we express 1234567654321 as 12345...54321, but 1234567 is represented as 1234567. Finally, represent the product as a string "<pre>...<suf>eC". For example, 12345678987600000 will be represented as "12345...89876e5". Return a string denoting the abbreviated product of all integers in the inclusive range [left, right]. Example 1: Input: left = 1, right = 4 Output: "24e0" Explanation: The product is 1 Γ— 2 Γ— 3 Γ— 4 = 24. There are no trailing zeros, so 24 remains the same. The abbreviation will end with "e0". Since the number of digits is 2, which is less than 10, we do not have to abbreviate it further. Thus, the final representation is "24e0". Example 2: Input: left = 2, right = 11 Output: "399168e2" Explanation: The product is 39916800. There are 2 trailing zeros, which we remove to get 399168. The abbreviation will end with "e2". The number of digits after removing the trailing zeros is 6, so we do not abbreviate it further. Hence, the abbreviated product is "399168e2". Example 3: Input: left = 371, right = 375 Output: "7219856259e3" Explanation: The product is 7219856259000. Constraints: 1 <= left <= right <= 104
[Python3] quasi brute-force
525
abbreviating-the-product-of-a-range
0.28
ye15
Hard
29,260
2,117
a number after a double reversal
class Solution: def isSameAfterReversals(self, num: int) -> bool: return not num or num % 10
https://leetcode.com/problems/a-number-after-a-double-reversal/discuss/1648940/Python3-1-Liner-or-O(1)-Time-and-Space-or-Short-and-Clean-Explanation
12
Reversing an integer means to reverse all its digits. For example, reversing 2021 gives 1202. Reversing 12300 gives 321 as the leading zeros are not retained. Given an integer num, reverse num to get reversed1, then reverse reversed1 to get reversed2. Return true if reversed2 equals num. Otherwise return false. Example 1: Input: num = 526 Output: true Explanation: Reverse num to get 625, then reverse 625 to get 526, which equals num. Example 2: Input: num = 1800 Output: false Explanation: Reverse num to get 81, then reverse 81 to get 18, which does not equal num. Example 3: Input: num = 0 Output: true Explanation: Reverse num to get 0, then reverse 0 to get 0, which equals num. Constraints: 0 <= num <= 106
[Python3] 1 Liner | O(1) Time and Space | Short and Clean Explanation
578
a-number-after-a-double-reversal
0.758
PatrickOweijane
Easy
29,265
2,119
execution of all suffix instructions staying in a grid
class Solution: def executeInstructions(self, n: int, startPos: list[int], s: str) -> list[int]: def num_of_valid_instructions(s, pos, start, end): row, colon = pos k = 0 for i in range(start, end): cur = s[i] row += (cur == 'D') - (cur == 'U') colon += (cur == 'R') - (cur == 'L') if not (0 <= row < n and 0 <= colon < n): return k k += 1 return k ans = [] for i in range(len(s)): ans.append(num_of_valid_instructions(s, startPos, i, len(s))) return ans
https://leetcode.com/problems/execution-of-all-suffix-instructions-staying-in-a-grid/discuss/2838969/Python-Straight-forward-O(n-2)-solution-(still-fast-85)
1
There is an n x n grid, with the top-left cell at (0, 0) and the bottom-right cell at (n - 1, n - 1). You are given the integer n and an integer array startPos where startPos = [startrow, startcol] indicates that a robot is initially at cell (startrow, startcol). You are also given a 0-indexed string s of length m where s[i] is the ith instruction for the robot: 'L' (move left), 'R' (move right), 'U' (move up), and 'D' (move down). The robot can begin executing from any ith instruction in s. It executes the instructions one by one towards the end of s but it stops if either of these conditions is met: The next instruction will move the robot off the grid. There are no more instructions left to execute. Return an array answer of length m where answer[i] is the number of instructions the robot can execute if the robot begins executing from the ith instruction in s. Example 1: Input: n = 3, startPos = [0,1], s = "RRDDLU" Output: [1,5,4,3,1,0] Explanation: Starting from startPos and beginning execution from the ith instruction: - 0th: "RRDDLU". Only one instruction "R" can be executed before it moves off the grid. - 1st: "RDDLU". All five instructions can be executed while it stays in the grid and ends at (1, 1). - 2nd: "DDLU". All four instructions can be executed while it stays in the grid and ends at (1, 0). - 3rd: "DLU". All three instructions can be executed while it stays in the grid and ends at (0, 0). - 4th: "LU". Only one instruction "L" can be executed before it moves off the grid. - 5th: "U". If moving up, it would move off the grid. Example 2: Input: n = 2, startPos = [1,1], s = "LURD" Output: [4,1,0,0] Explanation: - 0th: "LURD". - 1st: "URD". - 2nd: "RD". - 3rd: "D". Example 3: Input: n = 1, startPos = [0,0], s = "LRUD" Output: [0,0,0,0] Explanation: No matter which instruction the robot begins execution from, it would move off the grid. Constraints: m == s.length 1 <= n, m <= 500 startPos.length == 2 0 <= startrow, startcol < n s consists of 'L', 'R', 'U', and 'D'.
[Python] Straight-forward O(n ^ 2) solution (still fast - 85%)
4
execution-of-all-suffix-instructions-staying-in-a-grid
0.836
Mark_computer
Medium
29,307
2,120
intervals between identical elements
class Solution: def getDistances(self, arr: List[int]) -> List[int]: loc = defaultdict(list) for i, x in enumerate(arr): loc[x].append(i) for k, idx in loc.items(): prefix = list(accumulate(idx, initial=0)) vals = [] for i, x in enumerate(idx): vals.append(prefix[-1] - prefix[i] - prefix[i+1] - (len(idx)-2*i-1)*x) loc[k] = deque(vals) return [loc[x].popleft() for x in arr]
https://leetcode.com/problems/intervals-between-identical-elements/discuss/1647480/Python3-prefix-sum
9
You are given a 0-indexed array of n integers arr. The interval between two elements in arr is defined as the absolute difference between their indices. More formally, the interval between arr[i] and arr[j] is |i - j|. Return an array intervals of length n where intervals[i] is the sum of intervals between arr[i] and each element in arr with the same value as arr[i]. Note: |x| is the absolute value of x. Example 1: Input: arr = [2,1,3,1,2,3,3] Output: [4,2,7,2,4,4,5] Explanation: - Index 0: Another 2 is found at index 4. |0 - 4| = 4 - Index 1: Another 1 is found at index 3. |1 - 3| = 2 - Index 2: Two more 3s are found at indices 5 and 6. |2 - 5| + |2 - 6| = 7 - Index 3: Another 1 is found at index 1. |3 - 1| = 2 - Index 4: Another 2 is found at index 0. |4 - 0| = 4 - Index 5: Two more 3s are found at indices 2 and 6. |5 - 2| + |5 - 6| = 4 - Index 6: Two more 3s are found at indices 2 and 5. |6 - 2| + |6 - 5| = 5 Example 2: Input: arr = [10,5,10,10] Output: [5,0,3,4] Explanation: - Index 0: Two more 10s are found at indices 2 and 3. |0 - 2| + |0 - 3| = 5 - Index 1: There is only one 5 in the array, so its sum of intervals to identical elements is 0. - Index 2: Two more 10s are found at indices 0 and 3. |2 - 0| + |2 - 3| = 3 - Index 3: Two more 10s are found at indices 0 and 2. |3 - 0| + |3 - 2| = 4 Constraints: n == arr.length 1 <= n <= 105 1 <= arr[i] <= 105
[Python3] prefix sum
1,100
intervals-between-identical-elements
0.433
ye15
Medium
29,326
2,121
recover the original array
class Solution: def recoverArray(self, nums: List[int]) -> List[int]: nums.sort() cnt = Counter(nums) for i in range(1, len(nums)): diff = nums[i] - nums[0] if diff and diff&amp;1 == 0: ans = [] freq = cnt.copy() for k, v in freq.items(): if v: if freq[k+diff] < v: break ans.extend([k+diff//2]*v) freq[k+diff] -= v else: return ans
https://leetcode.com/problems/recover-the-original-array/discuss/1647488/Python3-brute-force
11
Alice had a 0-indexed array arr consisting of n positive integers. She chose an arbitrary positive integer k and created two new 0-indexed integer arrays lower and higher in the following manner: lower[i] = arr[i] - k, for every index i where 0 <= i < n higher[i] = arr[i] + k, for every index i where 0 <= i < n Unfortunately, Alice lost all three arrays. However, she remembers the integers that were present in the arrays lower and higher, but not the array each integer belonged to. Help Alice and recover the original array. Given an array nums consisting of 2n integers, where exactly n of the integers were present in lower and the remaining in higher, return the original array arr. In case the answer is not unique, return any valid array. Note: The test cases are generated such that there exists at least one valid array arr. Example 1: Input: nums = [2,10,6,4,8,12] Output: [3,7,11] Explanation: If arr = [3,7,11] and k = 1, we get lower = [2,6,10] and higher = [4,8,12]. Combining lower and higher gives us [2,6,10,4,8,12], which is a permutation of nums. Another valid possibility is that arr = [5,7,9] and k = 3. In that case, lower = [2,4,6] and higher = [8,10,12]. Example 2: Input: nums = [1,1,3,3] Output: [2,2] Explanation: If arr = [2,2] and k = 1, we get lower = [1,1] and higher = [3,3]. Combining lower and higher gives us [1,1,3,3], which is equal to nums. Note that arr cannot be [1,3] because in that case, the only possible way to obtain [1,1,3,3] is with k = 0. This is invalid since k must be positive. Example 3: Input: nums = [5,435] Output: [220] Explanation: The only possible combination is arr = [220] and k = 215. Using them, we get lower = [5] and higher = [435]. Constraints: 2 * n == nums.length 1 <= n <= 1000 1 <= nums[i] <= 109 The test cases are generated such that there exists at least one valid array arr.
[Python3] brute-force
503
recover-the-original-array
0.381
ye15
Hard
29,336
2,122
check if all as appears before all bs
class Solution: def checkString(self, s: str) -> bool: return ''.join(sorted(s)) == s
https://leetcode.com/problems/check-if-all-as-appears-before-all-bs/discuss/1662586/Python-O(NlogN)-sort-solution-and-O(N)-linear-scan-solution
4
Given a string s consisting of only the characters 'a' and 'b', return true if every 'a' appears before every 'b' in the string. Otherwise, return false. Example 1: Input: s = "aaabbb" Output: true Explanation: The 'a's are at indices 0, 1, and 2, while the 'b's are at indices 3, 4, and 5. Hence, every 'a' appears before every 'b' and we return true. Example 2: Input: s = "abab" Output: false Explanation: There is an 'a' at index 2 and a 'b' at index 1. Hence, not every 'a' appears before every 'b' and we return false. Example 3: Input: s = "bbb" Output: true Explanation: There are no 'a's, hence, every 'a' appears before every 'b' and we return true. Constraints: 1 <= s.length <= 100 s[i] is either 'a' or 'b'.
[Python] O(NlogN) sort solution and O(N) linear scan solution
193
check-if-all-as-appears-before-all-bs
0.716
kryuki
Easy
29,341
2,124
number of laser beams in a bank
class Solution: def numberOfBeams(self, bank: List[str]) -> int: a, s = [x.count("1") for x in bank if x.count("1")], 0 # ex: bank is [[00101], [01001], [00000], [11011]] # a would return [2, 2, 4] for c in range(len(a)-1): s += (a[c]*a[c+1]) # basic math to find the total amount of lasers # for the first iteration: s += 2*2 # for the second iteration: s += 2*4 # returns s = 12 return s
https://leetcode.com/problems/number-of-laser-beams-in-a-bank/discuss/2272999/PYTHON-3-99.13-LESS-MEMORY-or-94.93-FASTER-or-EXPLANATION
7
Anti-theft security devices are activated inside a bank. You are given a 0-indexed binary string array bank representing the floor plan of the bank, which is an m x n 2D matrix. bank[i] represents the ith row, consisting of '0's and '1's. '0' means the cell is empty, while'1' means the cell has a security device. There is one laser beam between any two security devices if both conditions are met: The two devices are located on two different rows: r1 and r2, where r1 < r2. For each row i where r1 < i < r2, there are no security devices in the ith row. Laser beams are independent, i.e., one beam does not interfere nor join with another. Return the total number of laser beams in the bank. Example 1: Input: bank = ["011001","000000","010100","001000"] Output: 8 Explanation: Between each of the following device pairs, there is one beam. In total, there are 8 beams: * bank[0][1] -- bank[2][1] * bank[0][1] -- bank[2][3] * bank[0][2] -- bank[2][1] * bank[0][2] -- bank[2][3] * bank[0][5] -- bank[2][1] * bank[0][5] -- bank[2][3] * bank[2][1] -- bank[3][2] * bank[2][3] -- bank[3][2] Note that there is no beam between any device on the 0th row with any on the 3rd row. This is because the 2nd row contains security devices, which breaks the second condition. Example 2: Input: bank = ["000","111","000"] Output: 0 Explanation: There does not exist two devices located on two different rows. Constraints: m == bank.length n == bank[i].length 1 <= m, n <= 500 bank[i][j] is either '0' or '1'.
[PYTHON 3] 99.13% LESS MEMORY | 94.93% FASTER | EXPLANATION
130
number-of-laser-beams-in-a-bank
0.826
omkarxpatel
Medium
29,379
2,125
destroying asteroids
class Solution: def asteroidsDestroyed(self, mass: int, asteroids: List[int]) -> bool: asteroids = sorted(asteroids) for i in asteroids: if i <= mass: mass += i else: return False return True
https://leetcode.com/problems/destroying-asteroids/discuss/1775912/Simple-python-solution-or-85-lesser-memory
2
You are given an integer mass, which represents the original mass of a planet. You are further given an integer array asteroids, where asteroids[i] is the mass of the ith asteroid. You can arrange for the planet to collide with the asteroids in any arbitrary order. If the mass of the planet is greater than or equal to the mass of the asteroid, the asteroid is destroyed and the planet gains the mass of the asteroid. Otherwise, the planet is destroyed. Return true if all asteroids can be destroyed. Otherwise, return false. Example 1: Input: mass = 10, asteroids = [3,9,19,5,21] Output: true Explanation: One way to order the asteroids is [9,19,5,3,21]: - The planet collides with the asteroid with a mass of 9. New planet mass: 10 + 9 = 19 - The planet collides with the asteroid with a mass of 19. New planet mass: 19 + 19 = 38 - The planet collides with the asteroid with a mass of 5. New planet mass: 38 + 5 = 43 - The planet collides with the asteroid with a mass of 3. New planet mass: 43 + 3 = 46 - The planet collides with the asteroid with a mass of 21. New planet mass: 46 + 21 = 67 All asteroids are destroyed. Example 2: Input: mass = 5, asteroids = [4,9,23,4] Output: false Explanation: The planet cannot ever gain enough mass to destroy the asteroid with a mass of 23. After the planet destroys the other asteroids, it will have a mass of 5 + 4 + 9 + 4 = 22. This is less than 23, so a collision would not destroy the last asteroid. Constraints: 1 <= mass <= 105 1 <= asteroids.length <= 105 1 <= asteroids[i] <= 105
βœ”Simple python solution | 85% lesser memory
129
destroying-asteroids
0.495
Coding_Tan3
Medium
29,412
2,126
maximum employees to be invited to a meeting
class Solution: def maximumInvitations(self, favorite: List[int]) -> int: n = len(favorite) graph = [[] for _ in range(n)] for i, x in enumerate(favorite): graph[x].append(i) def bfs(x, seen): """Return longest arm of x.""" ans = 0 queue = deque([x]) while queue: for _ in range(len(queue)): u = queue.popleft() for v in graph[u]: if v not in seen: seen.add(v) queue.append(v) ans += 1 return ans ans = 0 seen = [False]*n for i, x in enumerate(favorite): if favorite[x] == i and not seen[i]: seen[i] = seen[x] = True ans += bfs(i, {i, x}) + bfs(x, {i, x}) dp = [0]*n for i, x in enumerate(favorite): if dp[i] == 0: ii, val = i, 0 memo = {} while ii not in memo: if dp[ii]: cycle = dp[ii] break memo[ii] = val val += 1 ii = favorite[ii] else: cycle = val - memo[ii] for k in memo: dp[k] = cycle return max(ans, max(dp))
https://leetcode.com/problems/maximum-employees-to-be-invited-to-a-meeting/discuss/1661041/Python3-quite-a-tedious-solution
5
A company is organizing a meeting and has a list of n employees, waiting to be invited. They have arranged for a large circular table, capable of seating any number of employees. The employees are numbered from 0 to n - 1. Each employee has a favorite person and they will attend the meeting only if they can sit next to their favorite person at the table. The favorite person of an employee is not themself. Given a 0-indexed integer array favorite, where favorite[i] denotes the favorite person of the ith employee, return the maximum number of employees that can be invited to the meeting. Example 1: Input: favorite = [2,2,1,2] Output: 3 Explanation: The above figure shows how the company can invite employees 0, 1, and 2, and seat them at the round table. All employees cannot be invited because employee 2 cannot sit beside employees 0, 1, and 3, simultaneously. Note that the company can also invite employees 1, 2, and 3, and give them their desired seats. The maximum number of employees that can be invited to the meeting is 3. Example 2: Input: favorite = [1,2,0] Output: 3 Explanation: Each employee is the favorite person of at least one other employee, and the only way the company can invite them is if they invite every employee. The seating arrangement will be the same as that in the figure given in example 1: - Employee 0 will sit between employees 2 and 1. - Employee 1 will sit between employees 0 and 2. - Employee 2 will sit between employees 1 and 0. The maximum number of employees that can be invited to the meeting is 3. Example 3: Input: favorite = [3,0,1,4,1] Output: 4 Explanation: The above figure shows how the company will invite employees 0, 1, 3, and 4, and seat them at the round table. Employee 2 cannot be invited because the two spots next to their favorite employee 1 are taken. So the company leaves them out of the meeting. The maximum number of employees that can be invited to the meeting is 4. Constraints: n == favorite.length 2 <= n <= 105 0 <= favorite[i] <= n - 1 favorite[i] != i
[Python3] quite a tedious solution
1,000
maximum-employees-to-be-invited-to-a-meeting
0.337
ye15
Hard
29,427
2,127
capitalize the title
class Solution: def capitalizeTitle(self, title: str) -> str: title = title.split() word = "" for i in range(len(title)): if len(title[i]) < 3: word = word + title[i].lower() + " " else: word = word + title[i].capitalize() + " " return word[:-1]
https://leetcode.com/problems/capitalize-the-title/discuss/1716077/Python-Easy-Solution
4
You are given a string title consisting of one or more words separated by a single space, where each word consists of English letters. Capitalize the string by changing the capitalization of each word such that: If the length of the word is 1 or 2 letters, change all letters to lowercase. Otherwise, change the first letter to uppercase and the remaining letters to lowercase. Return the capitalized title. Example 1: Input: title = "capiTalIze tHe titLe" Output: "Capitalize The Title" Explanation: Since all the words have a length of at least 3, the first letter of each word is uppercase, and the remaining letters are lowercase. Example 2: Input: title = "First leTTeR of EACH Word" Output: "First Letter of Each Word" Explanation: The word "of" has length 2, so it is all lowercase. The remaining words have a length of at least 3, so the first letter of each remaining word is uppercase, and the remaining letters are lowercase. Example 3: Input: title = "i lOve leetcode" Output: "i Love Leetcode" Explanation: The word "i" has length 1, so it is lowercase. The remaining words have a length of at least 3, so the first letter of each remaining word is uppercase, and the remaining letters are lowercase. Constraints: 1 <= title.length <= 100 title consists of words separated by a single space without any leading or trailing spaces. Each word consists of uppercase and lowercase English letters and is non-empty.
Python Easy Solution
413
capitalize-the-title
0.603
yashitanamdeo
Easy
29,428
2,129
maximum twin sum of a linked list
class Solution: def pairSum(self, head: Optional[ListNode]) -> int: nums = [] curr = head while curr: nums.append(curr.val) curr = curr.next N = len(nums) res = 0 for i in range(N // 2): res = max(res, nums[i] + nums[N - i - 1]) return res
https://leetcode.com/problems/maximum-twin-sum-of-a-linked-list/discuss/1676025/Need-to-know-O(1)-space-solution-in-Python
16
In a linked list of size n, where n is even, the ith node (0-indexed) of the linked list is known as the twin of the (n-1-i)th node, if 0 <= i <= (n / 2) - 1. For example, if n = 4, then node 0 is the twin of node 3, and node 1 is the twin of node 2. These are the only nodes with twins for n = 4. The twin sum is defined as the sum of a node and its twin. Given the head of a linked list with even length, return the maximum twin sum of the linked list. Example 1: Input: head = [5,4,2,1] Output: 6 Explanation: Nodes 0 and 1 are the twins of nodes 3 and 2, respectively. All have twin sum = 6. There are no other nodes with twins in the linked list. Thus, the maximum twin sum of the linked list is 6. Example 2: Input: head = [4,2,2,3] Output: 7 Explanation: The nodes with twins present in this linked list are: - Node 0 is the twin of node 3 having a twin sum of 4 + 3 = 7. - Node 1 is the twin of node 2 having a twin sum of 2 + 2 = 4. Thus, the maximum twin sum of the linked list is max(7, 4) = 7. Example 3: Input: head = [1,100000] Output: 100001 Explanation: There is only one node with a twin in the linked list having twin sum of 1 + 100000 = 100001. Constraints: The number of nodes in the list is an even integer in the range [2, 105]. 1 <= Node.val <= 105
Need-to-know O(1) space solution in Python
1,900
maximum-twin-sum-of-a-linked-list
0.814
kryuki
Medium
29,470
2,130
longest palindrome by concatenating two letter words
class Solution: def longestPalindrome(self, words: List[str]) -> int: dc=defaultdict(lambda:0) for a in words: dc[a]+=1 count=0 palindromswords=0 inmiddle=0 wds=set(words) for a in wds: if(a==a[::-1]): if(dc[a]%2==1): inmiddle=1 palindromswords+=(dc[a]//2)*2 elif(dc[a[::-1]]>0): count+=(2*(min(dc[a],dc[a[::-1]]))) dc[a]=0 return (palindromswords+count+inmiddle)*2 ``
https://leetcode.com/problems/longest-palindrome-by-concatenating-two-letter-words/discuss/2772128/using-dictnory-in-TCN
5
You are given an array of strings words. Each element of words consists of two lowercase English letters. Create the longest possible palindrome by selecting some elements from words and concatenating them in any order. Each element can be selected at most once. Return the length of the longest palindrome that you can create. If it is impossible to create any palindrome, return 0. A palindrome is a string that reads the same forward and backward. Example 1: Input: words = ["lc","cl","gg"] Output: 6 Explanation: One longest palindrome is "lc" + "gg" + "cl" = "lcggcl", of length 6. Note that "clgglc" is another longest palindrome that can be created. Example 2: Input: words = ["ab","ty","yt","lc","cl","ab"] Output: 8 Explanation: One longest palindrome is "ty" + "lc" + "cl" + "yt" = "tylcclyt", of length 8. Note that "lcyttycl" is another longest palindrome that can be created. Example 3: Input: words = ["cc","ll","xx"] Output: 2 Explanation: One longest palindrome is "cc", of length 2. Note that "ll" is another longest palindrome that can be created, and so is "xx". Constraints: 1 <= words.length <= 105 words[i].length == 2 words[i] consists of lowercase English letters.
using dictnory in TC=N
349
longest-palindrome-by-concatenating-two-letter-words
0.491
droj
Medium
29,493
2,131
stamping the grid
class Solution: def prefix_sum(self, grid: List[List[int]]) -> List[List[int]]: ps = [[grid[row][col] for col in range(len(grid[0]))]for row in range(len(grid))] for row in range(len(grid)): for col in range(1, len(grid[0])): ps[row][col] = ps[row][col-1] + grid[row][col] for row in range(1, len(grid)): for col in range(len(grid[0])): ps[row][col] = ps[row-1][col] + ps[row][col] return ps def sumRegion(self, ps, row1: int, col1: int, row2: int, col2: int) -> int: ans = 0 if row1 == 0 and col1 == 0: ans = ps[row2][col2] elif row1 == 0: ans = ps[row2][col2] - ps[row2][col1-1] elif col1 == 0: ans = ps[row2][col2] - ps[row1-1][col2] else: ans = ps[row2][col2] - ps[row1-1][col2] - ps[row2][col1-1] + ps[row1-1][col1-1] return ans def possibleToStamp(self, grid: List[List[int]], stampHeight: int, stampWidth: int) -> bool: diff = [[0 for col in range(len(grid[0])+1)]for row in range(len(grid)+1)] ps = self.prefix_sum(grid) cover = 0 for row in range(len(grid)-(stampHeight-1)): for col in range(len(grid[0])-(stampWidth-1)): sub_sum = self.sumRegion(ps, row, col, row+stampHeight-1, col+stampWidth-1) if sub_sum == 0: diff[row][col] += 1 diff[row][col+stampWidth] -= 1 diff[row+stampHeight][col] -= 1 diff[row+stampHeight][col+stampWidth] = 1 pref_diff = self.prefix_sum(diff) m, n = len(grid), len(grid[0]) for row in range(len(grid)): for col in range(len(grid[0])): if grid[row][col] == 0 and pref_diff[row][col] == 0: return False return True
https://leetcode.com/problems/stamping-the-grid/discuss/2489712/Python3-solution%3A-faster-than-most-submissions-oror-Very-simple
0
You are given an m x n binary matrix grid where each cell is either 0 (empty) or 1 (occupied). You are then given stamps of size stampHeight x stampWidth. We want to fit the stamps such that they follow the given restrictions and requirements: Cover all the empty cells. Do not cover any of the occupied cells. We can put as many stamps as we want. Stamps can overlap with each other. Stamps are not allowed to be rotated. Stamps must stay completely inside the grid. Return true if it is possible to fit the stamps while following the given restrictions and requirements. Otherwise, return false. Example 1: Input: grid = [[1,0,0,0],[1,0,0,0],[1,0,0,0],[1,0,0,0],[1,0,0,0]], stampHeight = 4, stampWidth = 3 Output: true Explanation: We have two overlapping stamps (labeled 1 and 2 in the image) that are able to cover all the empty cells. Example 2: Input: grid = [[1,0,0,0],[0,1,0,0],[0,0,1,0],[0,0,0,1]], stampHeight = 2, stampWidth = 2 Output: false Explanation: There is no way to fit the stamps onto all the empty cells without the stamps going outside the grid. Constraints: m == grid.length n == grid[r].length 1 <= m, n <= 105 1 <= m * n <= 2 * 105 grid[r][c] is either 0 or 1. 1 <= stampHeight, stampWidth <= 105
βœ”οΈ Python3 solution: faster than most submissions || Very simple
40
stamping-the-grid
0.309
Omegang
Hard
29,544
2,132
check if every row and column contains all numbers
class Solution: def checkValid(self, matrix: List[List[int]]) -> bool: lst = [0]*len(matrix) for i in matrix: if len(set(i)) != len(matrix): return False for j in range(len(i)): lst[j] += i[j] return len(set(lst)) == 1
https://leetcode.com/problems/check-if-every-row-and-column-contains-all-numbers/discuss/1775747/Python-3-or-7-Line-solution-or-87-Faster-runtime-or-92.99-lesser-memory
6
An n x n matrix is valid if every row and every column contains all the integers from 1 to n (inclusive). Given an n x n integer matrix matrix, return true if the matrix is valid. Otherwise, return false. Example 1: Input: matrix = [[1,2,3],[3,1,2],[2,3,1]] Output: true Explanation: In this case, n = 3, and every row and column contains the numbers 1, 2, and 3. Hence, we return true. Example 2: Input: matrix = [[1,1,1],[1,2,3],[1,2,3]] Output: false Explanation: In this case, n = 3, but the first row and the first column do not contain the numbers 2 or 3. Hence, we return false. Constraints: n == matrix.length == matrix[i].length 1 <= n <= 100 1 <= matrix[i][j] <= n
βœ”Python 3 | 7 Line solution | 87% Faster runtime | 92.99% lesser memory
855
check-if-every-row-and-column-contains-all-numbers
0.53
Coding_Tan3
Easy
29,546
2,133
minimum swaps to group all 1s together ii
class Solution: def minSwaps(self, nums: List[int]) -> int: width = sum(num == 1 for num in nums) #width of the window nums += nums res = width curr_zeros = sum(num == 0 for num in nums[:width]) #the first window is nums[:width] for i in range(width, len(nums)): curr_zeros -= (nums[i - width] == 0) #remove the leftmost 0 if exists curr_zeros += (nums[i] == 0) #add the rightmost 0 if exists res = min(res, curr_zeros) #update if needed return res
https://leetcode.com/problems/minimum-swaps-to-group-all-1s-together-ii/discuss/1677262/Sliding-window-with-comments-Python
21
A swap is defined as taking two distinct positions in an array and swapping the values in them. A circular array is defined as an array where we consider the first element and the last element to be adjacent. Given a binary circular array nums, return the minimum number of swaps required to group all 1's present in the array together at any location. Example 1: Input: nums = [0,1,0,1,1,0,0] Output: 1 Explanation: Here are a few of the ways to group all the 1's together: [0,0,1,1,1,0,0] using 1 swap. [0,1,1,1,0,0,0] using 1 swap. [1,1,0,0,0,0,1] using 2 swaps (using the circular property of the array). There is no way to group all 1's together with 0 swaps. Thus, the minimum number of swaps required is 1. Example 2: Input: nums = [0,1,1,1,0,0,1,1,0] Output: 2 Explanation: Here are a few of the ways to group all the 1's together: [1,1,1,0,0,0,0,1,1] using 2 swaps (using the circular property of the array). [1,1,1,1,1,0,0,0,0] using 2 swaps. There is no way to group all 1's together with 0 or 1 swaps. Thus, the minimum number of swaps required is 2. Example 3: Input: nums = [1,1,0,0,1] Output: 0 Explanation: All the 1's are already grouped together due to the circular property of the array. Thus, the minimum number of swaps required is 0. Constraints: 1 <= nums.length <= 105 nums[i] is either 0 or 1.
Sliding window with comments, Python
645
minimum-swaps-to-group-all-1s-together-ii
0.507
kryuki
Medium
29,587
2,134
count words obtained after adding a letter
class Solution: def wordCount(self, startWords: List[str], targetWords: List[str]) -> int: seen = set() for word in startWords: m = 0 for ch in word: m ^= 1 << ord(ch)-97 seen.add(m) ans = 0 for word in targetWords: m = 0 for ch in word: m ^= 1 << ord(ch)-97 for ch in word: if m ^ (1 << ord(ch)-97) in seen: ans += 1 break return ans
https://leetcode.com/problems/count-words-obtained-after-adding-a-letter/discuss/1676852/Python3-bitmask
84
You are given two 0-indexed arrays of strings startWords and targetWords. Each string consists of lowercase English letters only. For each string in targetWords, check if it is possible to choose a string from startWords and perform a conversion operation on it to be equal to that from targetWords. The conversion operation is described in the following two steps: Append any lowercase letter that is not present in the string to its end. For example, if the string is "abc", the letters 'd', 'e', or 'y' can be added to it, but not 'a'. If 'd' is added, the resulting string will be "abcd". Rearrange the letters of the new string in any arbitrary order. For example, "abcd" can be rearranged to "acbd", "bacd", "cbda", and so on. Note that it can also be rearranged to "abcd" itself. Return the number of strings in targetWords that can be obtained by performing the operations on any string of startWords. Note that you will only be verifying if the string in targetWords can be obtained from a string in startWords by performing the operations. The strings in startWords do not actually change during this process. Example 1: Input: startWords = ["ant","act","tack"], targetWords = ["tack","act","acti"] Output: 2 Explanation: - In order to form targetWords[0] = "tack", we use startWords[1] = "act", append 'k' to it, and rearrange "actk" to "tack". - There is no string in startWords that can be used to obtain targetWords[1] = "act". Note that "act" does exist in startWords, but we must append one letter to the string before rearranging it. - In order to form targetWords[2] = "acti", we use startWords[1] = "act", append 'i' to it, and rearrange "acti" to "acti" itself. Example 2: Input: startWords = ["ab","a"], targetWords = ["abc","abcd"] Output: 1 Explanation: - In order to form targetWords[0] = "abc", we use startWords[0] = "ab", add 'c' to it, and rearrange it to "abc". - There is no string in startWords that can be used to obtain targetWords[1] = "abcd". Constraints: 1 <= startWords.length, targetWords.length <= 5 * 104 1 <= startWords[i].length, targetWords[j].length <= 26 Each string of startWords and targetWords consists of lowercase English letters only. No letter occurs more than once in any string of startWords or targetWords.
[Python3] bitmask
5,900
count-words-obtained-after-adding-a-letter
0.428
ye15
Medium
29,602
2,135
earliest possible day of full bloom
class Solution: def earliestFullBloom(self, plantTime: List[int], growTime: List[int]) -> int: res = 0 for grow, plant in sorted(zip(growTime, plantTime)): res = max(res, grow) + plant return res
https://leetcode.com/problems/earliest-possible-day-of-full-bloom/discuss/1676837/Grow-then-plant
203
You have n flower seeds. Every seed must be planted first before it can begin to grow, then bloom. Planting a seed takes time and so does the growth of a seed. You are given two 0-indexed integer arrays plantTime and growTime, of length n each: plantTime[i] is the number of full days it takes you to plant the ith seed. Every day, you can work on planting exactly one seed. You do not have to work on planting the same seed on consecutive days, but the planting of a seed is not complete until you have worked plantTime[i] days on planting it in total. growTime[i] is the number of full days it takes the ith seed to grow after being completely planted. After the last day of its growth, the flower blooms and stays bloomed forever. From the beginning of day 0, you can plant the seeds in any order. Return the earliest possible day where all seeds are blooming. Example 1: Input: plantTime = [1,4,3], growTime = [2,3,1] Output: 9 Explanation: The grayed out pots represent planting days, colored pots represent growing days, and the flower represents the day it blooms. One optimal way is: On day 0, plant the 0th seed. The seed grows for 2 full days and blooms on day 3. On days 1, 2, 3, and 4, plant the 1st seed. The seed grows for 3 full days and blooms on day 8. On days 5, 6, and 7, plant the 2nd seed. The seed grows for 1 full day and blooms on day 9. Thus, on day 9, all the seeds are blooming. Example 2: Input: plantTime = [1,2,3,2], growTime = [2,1,2,1] Output: 9 Explanation: The grayed out pots represent planting days, colored pots represent growing days, and the flower represents the day it blooms. One optimal way is: On day 1, plant the 0th seed. The seed grows for 2 full days and blooms on day 4. On days 0 and 3, plant the 1st seed. The seed grows for 1 full day and blooms on day 5. On days 2, 4, and 5, plant the 2nd seed. The seed grows for 2 full days and blooms on day 8. On days 6 and 7, plant the 3rd seed. The seed grows for 1 full day and blooms on day 9. Thus, on day 9, all the seeds are blooming. Example 3: Input: plantTime = [1], growTime = [1] Output: 2 Explanation: On day 0, plant the 0th seed. The seed grows for 1 full day and blooms on day 2. Thus, on day 2, all the seeds are blooming. Constraints: n == plantTime.length == growTime.length 1 <= n <= 105 1 <= plantTime[i], growTime[i] <= 104
Grow then plant
6,900
earliest-possible-day-of-full-bloom
0.749
votrubac
Hard
29,614
2,136
divide a string into groups of size k
class Solution: def divideString(self, s: str, k: int, fill: str) -> List[str]: length = len(s) res=[] for i in range(0,length,k): if i+k>length: break res.append(s[i:i+k]) mod =length%k if mod!= 0: fill_str = fill *(k-mod) add_str = s[i:]+fill_str res.append(add_str) return res
https://leetcode.com/problems/divide-a-string-into-groups-of-size-k/discuss/1694807/Python-O(n)-solution
2
A string s can be partitioned into groups of size k using the following procedure: The first group consists of the first k characters of the string, the second group consists of the next k characters of the string, and so on. Each character can be a part of exactly one group. For the last group, if the string does not have k characters remaining, a character fill is used to complete the group. Note that the partition is done so that after removing the fill character from the last group (if it exists) and concatenating all the groups in order, the resultant string should be s. Given the string s, the size of each group k and the character fill, return a string array denoting the composition of every group s has been divided into, using the above procedure. Example 1: Input: s = "abcdefghi", k = 3, fill = "x" Output: ["abc","def","ghi"] Explanation: The first 3 characters "abc" form the first group. The next 3 characters "def" form the second group. The last 3 characters "ghi" form the third group. Since all groups can be completely filled by characters from the string, we do not need to use fill. Thus, the groups formed are "abc", "def", and "ghi". Example 2: Input: s = "abcdefghij", k = 3, fill = "x" Output: ["abc","def","ghi","jxx"] Explanation: Similar to the previous example, we are forming the first three groups "abc", "def", and "ghi". For the last group, we can only use the character 'j' from the string. To complete this group, we add 'x' twice. Thus, the 4 groups formed are "abc", "def", "ghi", and "jxx". Constraints: 1 <= s.length <= 100 s consists of lowercase English letters only. 1 <= k <= 100 fill is a lowercase English letter.
Python O(n) solution
100
divide-a-string-into-groups-of-size-k
0.652
SamyakKrSahoo
Easy
29,649
2,138
minimum moves to reach target score
class Solution: def minMoves(self, target: int, maxDoubles: int) -> int: moves = 0 while maxDoubles > 0 and target > 1: if target % 2 == 1: target -= 1 else: target //= 2 maxDoubles -= 1 moves += 1 moves += target - 1 return moves
https://leetcode.com/problems/minimum-moves-to-reach-target-score/discuss/1722491/Easy-Solution-python-explained-30ms
2
You are playing a game with integers. You start with the integer 1 and you want to reach the integer target. In one move, you can either: Increment the current integer by one (i.e., x = x + 1). Double the current integer (i.e., x = 2 * x). You can use the increment operation any number of times, however, you can only use the double operation at most maxDoubles times. Given the two integers target and maxDoubles, return the minimum number of moves needed to reach target starting with 1. Example 1: Input: target = 5, maxDoubles = 0 Output: 4 Explanation: Keep incrementing by 1 until you reach target. Example 2: Input: target = 19, maxDoubles = 2 Output: 7 Explanation: Initially, x = 1 Increment 3 times so x = 4 Double once so x = 8 Increment once so x = 9 Double again so x = 18 Increment once so x = 19 Example 3: Input: target = 10, maxDoubles = 4 Output: 4 Explanation: Initially, x = 1 Increment once so x = 2 Double once so x = 4 Increment once so x = 5 Double again so x = 10 Constraints: 1 <= target <= 109 0 <= maxDoubles <= 100
Easy Solution python explained 30ms
83
minimum-moves-to-reach-target-score
0.484
Volver805
Medium
29,687
2,139
solving questions with brainpower
class Solution: def mostPoints(self, q: List[List[int]]) -> int: @cache def dfs(i: int) -> int: return 0 if i >= len(q) else max(dfs(i + 1), q[i][0] + dfs(i + 1 + q[i][1])) return dfs(0)
https://leetcode.com/problems/solving-questions-with-brainpower/discuss/1692963/DP
132
You are given a 0-indexed 2D integer array questions where questions[i] = [pointsi, brainpoweri]. The array describes the questions of an exam, where you have to process the questions in order (i.e., starting from question 0) and make a decision whether to solve or skip each question. Solving question i will earn you pointsi points but you will be unable to solve each of the next brainpoweri questions. If you skip question i, you get to make the decision on the next question. For example, given questions = [[3, 2], [4, 3], [4, 4], [2, 5]]: If question 0 is solved, you will earn 3 points but you will be unable to solve questions 1 and 2. If instead, question 0 is skipped and question 1 is solved, you will earn 4 points but you will be unable to solve questions 2 and 3. Return the maximum points you can earn for the exam. Example 1: Input: questions = [[3,2],[4,3],[4,4],[2,5]] Output: 5 Explanation: The maximum points can be earned by solving questions 0 and 3. - Solve question 0: Earn 3 points, will be unable to solve the next 2 questions - Unable to solve questions 1 and 2 - Solve question 3: Earn 2 points Total points earned: 3 + 2 = 5. There is no other way to earn 5 or more points. Example 2: Input: questions = [[1,1],[2,2],[3,3],[4,4],[5,5]] Output: 7 Explanation: The maximum points can be earned by solving questions 1 and 4. - Skip question 0 - Solve question 1: Earn 2 points, will be unable to solve the next 2 questions - Unable to solve questions 2 and 3 - Solve question 4: Earn 5 points Total points earned: 2 + 5 = 7. There is no other way to earn 7 or more points. Constraints: 1 <= questions.length <= 105 questions[i].length == 2 1 <= pointsi, brainpoweri <= 105
DP
5,500
solving-questions-with-brainpower
0.46
votrubac
Medium
29,711
2,140
maximum running time of n computers
class Solution: def maxRunTime(self, n: int, batteries: List[int]) -> int: batteries.sort() extra = sum(batteries[:-n]) batteries = batteries[-n:] ans = prefix = 0 for i, x in enumerate(batteries): prefix += x if i+1 < len(batteries) and batteries[i+1]*(i+1) - prefix > extra: return (prefix + extra) // (i+1) return (prefix + extra) // n
https://leetcode.com/problems/maximum-running-time-of-n-computers/discuss/1692965/Python3-greedy
39
You have n computers. You are given the integer n and a 0-indexed integer array batteries where the ith battery can run a computer for batteries[i] minutes. You are interested in running all n computers simultaneously using the given batteries. Initially, you can insert at most one battery into each computer. After that and at any integer time moment, you can remove a battery from a computer and insert another battery any number of times. The inserted battery can be a totally new battery or a battery from another computer. You may assume that the removing and inserting processes take no time. Note that the batteries cannot be recharged. Return the maximum number of minutes you can run all the n computers simultaneously. Example 1: Input: n = 2, batteries = [3,3,3] Output: 4 Explanation: Initially, insert battery 0 into the first computer and battery 1 into the second computer. After two minutes, remove battery 1 from the second computer and insert battery 2 instead. Note that battery 1 can still run for one minute. At the end of the third minute, battery 0 is drained, and you need to remove it from the first computer and insert battery 1 instead. By the end of the fourth minute, battery 1 is also drained, and the first computer is no longer running. We can run the two computers simultaneously for at most 4 minutes, so we return 4. Example 2: Input: n = 2, batteries = [1,1,1,1] Output: 2 Explanation: Initially, insert battery 0 into the first computer and battery 2 into the second computer. After one minute, battery 0 and battery 2 are drained so you need to remove them and insert battery 1 into the first computer and battery 3 into the second computer. After another minute, battery 1 and battery 3 are also drained so the first and second computers are no longer running. We can run the two computers simultaneously for at most 2 minutes, so we return 2. Constraints: 1 <= n <= batteries.length <= 105 1 <= batteries[i] <= 109
[Python3] greedy
1,400
maximum-running-time-of-n-computers
0.389
ye15
Hard
29,741
2,141
minimum cost of buying candies with discount
class Solution: def minimumCost(self, cost: List[int]) -> int: cost.sort(reverse=True) res, i, N = 0, 0, len(cost) while i < N: res += sum(cost[i : i + 2]) i += 3 return res
https://leetcode.com/problems/minimum-cost-of-buying-candies-with-discount/discuss/1712364/Python-Simple-solution-or-100-faster-or-O(N-logN)-Time-or-O(1)-Space
9
A shop is selling candies at a discount. For every two candies sold, the shop gives a third candy for free. The customer can choose any candy to take away for free as long as the cost of the chosen candy is less than or equal to the minimum cost of the two candies bought. For example, if there are 4 candies with costs 1, 2, 3, and 4, and the customer buys candies with costs 2 and 3, they can take the candy with cost 1 for free, but not the candy with cost 4. Given a 0-indexed integer array cost, where cost[i] denotes the cost of the ith candy, return the minimum cost of buying all the candies. Example 1: Input: cost = [1,2,3] Output: 5 Explanation: We buy the candies with costs 2 and 3, and take the candy with cost 1 for free. The total cost of buying all candies is 2 + 3 = 5. This is the only way we can buy the candies. Note that we cannot buy candies with costs 1 and 3, and then take the candy with cost 2 for free. The cost of the free candy has to be less than or equal to the minimum cost of the purchased candies. Example 2: Input: cost = [6,5,7,9,2,2] Output: 23 Explanation: The way in which we can get the minimum cost is described below: - Buy candies with costs 9 and 7 - Take the candy with cost 6 for free - We buy candies with costs 5 and 2 - Take the last remaining candy with cost 2 for free Hence, the minimum cost to buy all candies is 9 + 7 + 5 + 2 = 23. Example 3: Input: cost = [5,5] Output: 10 Explanation: Since there are only 2 candies, we buy both of them. There is not a third candy we can take for free. Hence, the minimum cost to buy all candies is 5 + 5 = 10. Constraints: 1 <= cost.length <= 100 1 <= cost[i] <= 100
[Python] Simple solution | 100% faster | O(N logN) Time | O(1) Space
454
minimum-cost-of-buying-candies-with-discount
0.609
eshikashah
Easy
29,744
2,144
count the hidden sequences
class Solution: def numberOfArrays(self, diff: List[int], lower: int, upper: int) -> int: diff = list(accumulate(diff, initial = 0)) return max(0, upper - lower - (max(diff) - min(diff)) + 1)
https://leetcode.com/problems/count-the-hidden-sequences/discuss/1714246/Right-Left
5
You are given a 0-indexed array of n integers differences, which describes the differences between each pair of consecutive integers of a hidden sequence of length (n + 1). More formally, call the hidden sequence hidden, then we have that differences[i] = hidden[i + 1] - hidden[i]. You are further given two integers lower and upper that describe the inclusive range of values [lower, upper] that the hidden sequence can contain. For example, given differences = [1, -3, 4], lower = 1, upper = 6, the hidden sequence is a sequence of length 4 whose elements are in between 1 and 6 (inclusive). [3, 4, 1, 5] and [4, 5, 2, 6] are possible hidden sequences. [5, 6, 3, 7] is not possible since it contains an element greater than 6. [1, 2, 3, 4] is not possible since the differences are not correct. Return the number of possible hidden sequences there are. If there are no possible sequences, return 0. Example 1: Input: differences = [1,-3,4], lower = 1, upper = 6 Output: 2 Explanation: The possible hidden sequences are: - [3, 4, 1, 5] - [4, 5, 2, 6] Thus, we return 2. Example 2: Input: differences = [3,-4,5,1,-2], lower = -4, upper = 5 Output: 4 Explanation: The possible hidden sequences are: - [-3, 0, -4, 1, 2, 0] - [-2, 1, -3, 2, 3, 1] - [-1, 2, -2, 3, 4, 2] - [0, 3, -1, 4, 5, 3] Thus, we return 4. Example 3: Input: differences = [4,-7,2], lower = 3, upper = 6 Output: 0 Explanation: There are no possible hidden sequences. Thus, we return 0. Constraints: n == differences.length 1 <= n <= 105 -105 <= differences[i] <= 105 -105 <= lower <= upper <= 105
Right - Left
266
count-the-hidden-sequences
0.365
votrubac
Medium
29,769
2,145
k highest ranked items within a price range
class Solution: def highestRankedKItems(self, grid: List[List[int]], pricing: List[int], start: List[int], k: int) -> List[List[int]]: m, n = len(grid), len(grid[0]) ans = [] queue = deque([(0, *start)]) grid[start[0]][start[1]] *= -1 while queue: x, i, j = queue.popleft() if pricing[0] <= -grid[i][j] <= pricing[1]: ans.append((x, -grid[i][j], i, j)) 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 grid[ii][jj] > 0: queue.append((x+1, ii, jj)) grid[ii][jj] *= -1 return [[i, j] for _, _, i, j in sorted(ans)[:k]]
https://leetcode.com/problems/k-highest-ranked-items-within-a-price-range/discuss/1709702/Python3-bfs
1
You are given a 0-indexed 2D integer array grid of size m x n that represents a map of the items in a shop. The integers in the grid represent the following: 0 represents a wall that you cannot pass through. 1 represents an empty cell that you can freely move to and from. All other positive integers represent the price of an item in that cell. You may also freely move to and from these item cells. It takes 1 step to travel between adjacent grid cells. You are also given integer arrays pricing and start where pricing = [low, high] and start = [row, col] indicates that you start at the position (row, col) and are interested only in items with a price in the range of [low, high] (inclusive). You are further given an integer k. You are interested in the positions of the k highest-ranked items whose prices are within the given price range. The rank is determined by the first of these criteria that is different: Distance, defined as the length of the shortest path from the start (shorter distance has a higher rank). Price (lower price has a higher rank, but it must be in the price range). The row number (smaller row number has a higher rank). The column number (smaller column number has a higher rank). Return the k highest-ranked items within the price range sorted by their rank (highest to lowest). If there are fewer than k reachable items within the price range, return all of them. Example 1: Input: grid = [[1,2,0,1],[1,3,0,1],[0,2,5,1]], pricing = [2,5], start = [0,0], k = 3 Output: [[0,1],[1,1],[2,1]] Explanation: You start at (0,0). With a price range of [2,5], we can take items from (0,1), (1,1), (2,1) and (2,2). The ranks of these items are: - (0,1) with distance 1 - (1,1) with distance 2 - (2,1) with distance 3 - (2,2) with distance 4 Thus, the 3 highest ranked items in the price range are (0,1), (1,1), and (2,1). Example 2: Input: grid = [[1,2,0,1],[1,3,3,1],[0,2,5,1]], pricing = [2,3], start = [2,3], k = 2 Output: [[2,1],[1,2]] Explanation: You start at (2,3). With a price range of [2,3], we can take items from (0,1), (1,1), (1,2) and (2,1). The ranks of these items are: - (2,1) with distance 2, price 2 - (1,2) with distance 2, price 3 - (1,1) with distance 3 - (0,1) with distance 4 Thus, the 2 highest ranked items in the price range are (2,1) and (1,2). Example 3: Input: grid = [[1,1,1],[0,0,1],[2,3,4]], pricing = [2,3], start = [0,0], k = 3 Output: [[2,1],[2,0]] Explanation: You start at (0,0). With a price range of [2,3], we can take items from (2,0) and (2,1). The ranks of these items are: - (2,1) with distance 5 - (2,0) with distance 6 Thus, the 2 highest ranked items in the price range are (2,1) and (2,0). Note that k = 3 but there are only 2 reachable items within the price range. Constraints: m == grid.length n == grid[i].length 1 <= m, n <= 105 1 <= m * n <= 105 0 <= grid[i][j] <= 105 pricing.length == 2 2 <= low <= high <= 105 start.length == 2 0 <= row <= m - 1 0 <= col <= n - 1 grid[row][col] > 0 1 <= k <= m * n
[Python3] bfs
32
k-highest-ranked-items-within-a-price-range
0.412
ye15
Medium
29,779
2,146
number of ways to divide a long corridor
class Solution: def numberOfWays(self, corridor: str) -> int: #edge case num_S = corridor.count('S') if num_S == 0 or num_S % 2 == 1: return 0 mod = 10 ** 9 + 7 curr_s = 0 divide_spots = [] for char in corridor: curr_s += (char == 'S') if curr_s > 0 and curr_s % 2 == 0: divide_spots[-1] += 1 else: if not divide_spots or divide_spots[-1] > 0: divide_spots.append(0) res = 1 for num in divide_spots[:-1]: res = res * num % mod return res
https://leetcode.com/problems/number-of-ways-to-divide-a-long-corridor/discuss/1709706/simple-Python-solution-(time%3A-O(N)-space%3A-O(1))
2
Along a long library corridor, there is a line of seats and decorative plants. You are given a 0-indexed string corridor of length n consisting of letters 'S' and 'P' where each 'S' represents a seat and each 'P' represents a plant. One room divider has already been installed to the left of index 0, and another to the right of index n - 1. Additional room dividers can be installed. For each position between indices i - 1 and i (1 <= i <= n - 1), at most one divider can be installed. Divide the corridor into non-overlapping sections, where each section has exactly two seats with any number of plants. There may be multiple ways to perform the division. Two ways are different if there is a position with a room divider installed in the first way but not in the second way. Return the number of ways to divide the corridor. Since the answer may be very large, return it modulo 109 + 7. If there is no way, return 0. Example 1: Input: corridor = "SSPPSPS" Output: 3 Explanation: There are 3 different ways to divide the corridor. The black bars in the above image indicate the two room dividers already installed. Note that in each of the ways, each section has exactly two seats. Example 2: Input: corridor = "PPSPSP" Output: 1 Explanation: There is only 1 way to divide the corridor, by not installing any additional dividers. Installing any would create some section that does not have exactly two seats. Example 3: Input: corridor = "S" Output: 0 Explanation: There is no way to divide the corridor because there will always be a section that does not have exactly two seats. Constraints: n == corridor.length 1 <= n <= 105 corridor[i] is either 'S' or 'P'.
simple Python solution (time: O(N), space: O(1))
92
number-of-ways-to-divide-a-long-corridor
0.399
kryuki
Hard
29,783
2,147
count elements with strictly smaller and greater elements
class Solution: def countElements(self, nums: List[int]) -> int: res = 0 mn = min(nums) mx = max(nums) for i in nums: if i > mn and i < mx: res += 1 return res
https://leetcode.com/problems/count-elements-with-strictly-smaller-and-greater-elements/discuss/2507825/Very-very-easy-code-in-just-3-lines-using-Python
7
Given an integer array nums, return the number of elements that have both a strictly smaller and a strictly greater element appear in nums. Example 1: Input: nums = [11,7,2,15] Output: 2 Explanation: The element 7 has the element 2 strictly smaller than it and the element 11 strictly greater than it. Element 11 has element 7 strictly smaller than it and element 15 strictly greater than it. In total there are 2 elements having both a strictly smaller and a strictly greater element appear in nums. Example 2: Input: nums = [-3,3,3,90] Output: 2 Explanation: The element 3 has the element -3 strictly smaller than it and the element 90 strictly greater than it. Since there are two elements with the value 3, in total there are 2 elements having both a strictly smaller and a strictly greater element appear in nums. Constraints: 1 <= nums.length <= 100 -105 <= nums[i] <= 105
Very very easy code in just 3 lines using Python
44
count-elements-with-strictly-smaller-and-greater-elements
0.6
ankurbhambri
Easy
29,793
2,148
rearrange array elements by sign
class Solution: def rearrangeArray(self, nums: List[int]) -> List[int]: return [i for t in zip([p for p in nums if p > 0], [n for n in nums if n < 0]) for i in t]
https://leetcode.com/problems/rearrange-array-elements-by-sign/discuss/1711329/Two-Pointers
20
You are given a 0-indexed integer array nums of even length consisting of an equal number of positive and negative integers. You should return the array of nums such that the the array follows the given conditions: Every consecutive pair of integers have opposite signs. For all integers with the same sign, the order in which they were present in nums is preserved. The rearranged array begins with a positive integer. Return the modified array after rearranging the elements to satisfy the aforementioned conditions. Example 1: Input: nums = [3,1,-2,-5,2,-4] Output: [3,-2,1,-5,2,-4] Explanation: The positive integers in nums are [3,1,2]. The negative integers are [-2,-5,-4]. The only possible way to rearrange them such that they satisfy all conditions is [3,-2,1,-5,2,-4]. Other ways such as [1,-2,2,-5,3,-4], [3,1,2,-2,-5,-4], [-2,3,-5,1,-4,2] are incorrect because they do not satisfy one or more conditions. Example 2: Input: nums = [-1,1] Output: [1,-1] Explanation: 1 is the only positive integer and -1 the only negative integer in nums. So nums is rearranged to [1,-1]. Constraints: 2 <= nums.length <= 2 * 105 nums.length is even 1 <= |nums[i]| <= 105 nums consists of equal number of positive and negative integers. It is not required to do the modifications in-place.
Two Pointers
5,200
rearrange-array-elements-by-sign
0.811
votrubac
Medium
29,821
2,149
find all lonely numbers in the array
class Solution: def findLonely(self, nums: List[int]) -> List[int]: m = Counter(nums) return [n for n in nums if m[n] == 1 and m[n - 1] + m[n + 1] == 0]
https://leetcode.com/problems/find-all-lonely-numbers-in-the-array/discuss/1711316/Counter
43
You are given an integer array nums. A number x is lonely when it appears only once, and no adjacent numbers (i.e. x + 1 and x - 1) appear in the array. Return all lonely numbers in nums. You may return the answer in any order. Example 1: Input: nums = [10,6,5,8] Output: [10,8] Explanation: - 10 is a lonely number since it appears exactly once and 9 and 11 does not appear in nums. - 8 is a lonely number since it appears exactly once and 7 and 9 does not appear in nums. - 5 is not a lonely number since 6 appears in nums and vice versa. Hence, the lonely numbers in nums are [10, 8]. Note that [8, 10] may also be returned. Example 2: Input: nums = [1,3,5,3] Output: [1,5] Explanation: - 1 is a lonely number since it appears exactly once and 0 and 2 does not appear in nums. - 5 is a lonely number since it appears exactly once and 4 and 6 does not appear in nums. - 3 is not a lonely number since it appears twice. Hence, the lonely numbers in nums are [1, 5]. Note that [5, 1] may also be returned. Constraints: 1 <= nums.length <= 105 0 <= nums[i] <= 106
Counter
3,400
find-all-lonely-numbers-in-the-array
0.608
votrubac
Medium
29,862
2,150
maximum good people based on statements
class Solution: def maximumGood(self, statements: List[List[int]]) -> int: ans, n = 0, len(statements) for person in itertools.product([0, 1], repeat=n): # use itertools to create a list only contains 0 or 1 valid = True # initially, we think the `person` list is valid for i in range(n): if not person[i]: continue # only `good` person's statement can lead to a contradiction, we don't care what `bad` person says for j in range(n): if statements[i][j] == 2: continue # ignore is no statement was made if statements[i][j] != person[j]: # if there is a contradiction, then valid = False valid = False break # optimization: break the loop when not valid if not valid: # optimization: break the loop when not valid break if valid: ans = max(ans, sum(person)) # count sum only when valid == True return ans
https://leetcode.com/problems/maximum-good-people-based-on-statements/discuss/1711677/Python-3-or-Itertools-and-Bitmask-or-Explanation
2
There are two types of persons: The good person: The person who always tells the truth. The bad person: The person who might tell the truth and might lie. You are given a 0-indexed 2D integer array statements of size n x n that represents the statements made by n people about each other. More specifically, statements[i][j] could be one of the following: 0 which represents a statement made by person i that person j is a bad person. 1 which represents a statement made by person i that person j is a good person. 2 represents that no statement is made by person i about person j. Additionally, no person ever makes a statement about themselves. Formally, we have that statements[i][i] = 2 for all 0 <= i < n. Return the maximum number of people who can be good based on the statements made by the n people. Example 1: Input: statements = [[2,1,2],[1,2,2],[2,0,2]] Output: 2 Explanation: Each person makes a single statement. - Person 0 states that person 1 is good. - Person 1 states that person 0 is good. - Person 2 states that person 1 is bad. Let's take person 2 as the key. - Assuming that person 2 is a good person: - Based on the statement made by person 2, person 1 is a bad person. - Now we know for sure that person 1 is bad and person 2 is good. - Based on the statement made by person 1, and since person 1 is bad, they could be: - telling the truth. There will be a contradiction in this case and this assumption is invalid. - lying. In this case, person 0 is also a bad person and lied in their statement. - Following that person 2 is a good person, there will be only one good person in the group. - Assuming that person 2 is a bad person: - Based on the statement made by person 2, and since person 2 is bad, they could be: - telling the truth. Following this scenario, person 0 and 1 are both bad as explained before. - Following that person 2 is bad but told the truth, there will be no good persons in the group. - lying. In this case person 1 is a good person. - Since person 1 is a good person, person 0 is also a good person. - Following that person 2 is bad and lied, there will be two good persons in the group. We can see that at most 2 persons are good in the best case, so we return 2. Note that there is more than one way to arrive at this conclusion. Example 2: Input: statements = [[2,0],[0,2]] Output: 1 Explanation: Each person makes a single statement. - Person 0 states that person 1 is bad. - Person 1 states that person 0 is bad. Let's take person 0 as the key. - Assuming that person 0 is a good person: - Based on the statement made by person 0, person 1 is a bad person and was lying. - Following that person 0 is a good person, there will be only one good person in the group. - Assuming that person 0 is a bad person: - Based on the statement made by person 0, and since person 0 is bad, they could be: - telling the truth. Following this scenario, person 0 and 1 are both bad. - Following that person 0 is bad but told the truth, there will be no good persons in the group. - lying. In this case person 1 is a good person. - Following that person 0 is bad and lied, there will be only one good person in the group. We can see that at most, one person is good in the best case, so we return 1. Note that there is more than one way to arrive at this conclusion. Constraints: n == statements.length == statements[i].length 2 <= n <= 15 statements[i][j] is either 0, 1, or 2. statements[i][i] == 2
Python 3 | Itertools & Bitmask | Explanation
126
maximum-good-people-based-on-statements
0.486
idontknoooo
Hard
29,880
2,151
keep multiplying found values by two
class Solution: def findFinalValue(self, nums: List[int], original: int) -> int: while original in nums: original *= 2 return original
https://leetcode.com/problems/keep-multiplying-found-values-by-two/discuss/2531609/Python-solution-simple-faster-than-80-less-memory-than-99
2
You are given an array of integers nums. You are also given an integer original which is the first number that needs to be searched for in nums. You then do the following steps: If original is found in nums, multiply it by two (i.e., set original = 2 * original). Otherwise, stop the process. Repeat this process with the new number as long as you keep finding the number. Return the final value of original. Example 1: Input: nums = [5,3,6,1,12], original = 3 Output: 24 Explanation: - 3 is found in nums. 3 is multiplied by 2 to obtain 6. - 6 is found in nums. 6 is multiplied by 2 to obtain 12. - 12 is found in nums. 12 is multiplied by 2 to obtain 24. - 24 is not found in nums. Thus, 24 is returned. Example 2: Input: nums = [2,7,9], original = 4 Output: 4 Explanation: - 4 is not found in nums. Thus, 4 is returned. Constraints: 1 <= nums.length <= 1000 1 <= nums[i], original <= 1000
Python solution simple faster than 80% less memory than 99%
62
keep-multiplying-found-values-by-two
0.731
Theo704
Easy
29,886
2,154
all divisions with the highest score of a binary array
class Solution: def maxScoreIndices(self, nums: List[int]) -> List[int]: ans = [0] cand = most = nums.count(1) for i, x in enumerate(nums): if x == 0: cand += 1 elif x == 1: cand -= 1 if cand > most: ans, most = [i+1], cand elif cand == most: ans.append(i+1) return ans
https://leetcode.com/problems/all-divisions-with-the-highest-score-of-a-binary-array/discuss/1732887/Python3-scan
2
You are given a 0-indexed binary array nums of length n. nums can be divided at index i (where 0 <= i <= n) into two arrays (possibly empty) numsleft and numsright: numsleft has all the elements of nums between index 0 and i - 1 (inclusive), while numsright has all the elements of nums between index i and n - 1 (inclusive). If i == 0, numsleft is empty, while numsright has all the elements of nums. If i == n, numsleft has all the elements of nums, while numsright is empty. The division score of an index i is the sum of the number of 0's in numsleft and the number of 1's in numsright. Return all distinct indices that have the highest possible division score. You may return the answer in any order. Example 1: Input: nums = [0,0,1,0] Output: [2,4] Explanation: Division at index - 0: numsleft is []. numsright is [0,0,1,0]. The score is 0 + 1 = 1. - 1: numsleft is [0]. numsright is [0,1,0]. The score is 1 + 1 = 2. - 2: numsleft is [0,0]. numsright is [1,0]. The score is 2 + 1 = 3. - 3: numsleft is [0,0,1]. numsright is [0]. The score is 2 + 0 = 2. - 4: numsleft is [0,0,1,0]. numsright is []. The score is 3 + 0 = 3. Indices 2 and 4 both have the highest possible division score 3. Note the answer [4,2] would also be accepted. Example 2: Input: nums = [0,0,0] Output: [3] Explanation: Division at index - 0: numsleft is []. numsright is [0,0,0]. The score is 0 + 0 = 0. - 1: numsleft is [0]. numsright is [0,0]. The score is 1 + 0 = 1. - 2: numsleft is [0,0]. numsright is [0]. The score is 2 + 0 = 2. - 3: numsleft is [0,0,0]. numsright is []. The score is 3 + 0 = 3. Only index 3 has the highest possible division score 3. Example 3: Input: nums = [1,1] Output: [0] Explanation: Division at index - 0: numsleft is []. numsright is [1,1]. The score is 0 + 2 = 2. - 1: numsleft is [1]. numsright is [1]. The score is 0 + 1 = 1. - 2: numsleft is [1,1]. numsright is []. The score is 0 + 0 = 0. Only index 0 has the highest possible division score 2. Constraints: n == nums.length 1 <= n <= 105 nums[i] is either 0 or 1.
[Python3] scan
39
all-divisions-with-the-highest-score-of-a-binary-array
0.634
ye15
Medium
29,934
2,155
find substring with given hash value
class Solution: def subStrHash(self, s: str, power: int, modulo: int, k: int, hashValue: int) -> str: pp = pow(power, k-1, modulo) hs = ii = 0 for i, ch in enumerate(reversed(s)): if i >= k: hs -= (ord(s[~(i-k)]) - 96)*pp hs = (hs * power + (ord(ch) - 96)) % modulo if i >= k-1 and hs == hashValue: ii = i return s[~ii:~ii+k or None]
https://leetcode.com/problems/find-substring-with-given-hash-value/discuss/1732936/Python3-rolling-hash
2
The hash of a 0-indexed string s of length k, given integers p and m, is computed using the following function: hash(s, p, m) = (val(s[0]) * p0 + val(s[1]) * p1 + ... + val(s[k-1]) * pk-1) mod m. Where val(s[i]) represents the index of s[i] in the alphabet from val('a') = 1 to val('z') = 26. You are given a string s and the integers power, modulo, k, and hashValue. Return sub, the first substring of s of length k such that hash(sub, power, modulo) == hashValue. The test cases will be generated such that an answer always exists. A substring is a contiguous non-empty sequence of characters within a string. Example 1: Input: s = "leetcode", power = 7, modulo = 20, k = 2, hashValue = 0 Output: "ee" Explanation: The hash of "ee" can be computed to be hash("ee", 7, 20) = (5 * 1 + 5 * 7) mod 20 = 40 mod 20 = 0. "ee" is the first substring of length 2 with hashValue 0. Hence, we return "ee". Example 2: Input: s = "fbxzaad", power = 31, modulo = 100, k = 3, hashValue = 32 Output: "fbx" Explanation: The hash of "fbx" can be computed to be hash("fbx", 31, 100) = (6 * 1 + 2 * 31 + 24 * 312) mod 100 = 23132 mod 100 = 32. The hash of "bxz" can be computed to be hash("bxz", 31, 100) = (2 * 1 + 24 * 31 + 26 * 312) mod 100 = 25732 mod 100 = 32. "fbx" is the first substring of length 3 with hashValue 32. Hence, we return "fbx". Note that "bxz" also has a hash of 32 but it appears later than "fbx". Constraints: 1 <= k <= s.length <= 2 * 104 1 <= power, modulo <= 109 0 <= hashValue < modulo s consists of lowercase English letters only. The test cases are generated such that an answer always exists.
[Python3] rolling hash
79
find-substring-with-given-hash-value
0.221
ye15
Hard
29,954
2,156
minimum sum of four digit number after splitting digits
class Solution: def minimumSum(self, num: int) -> int: num = sorted(str(num),reverse=True) n = len(num) res = 0 even_iteration = False position = 0 for i in range(n): res += int(num[i])*(10**position) if even_iteration: position += 1 even_iteration = False else: even_iteration = True return res
https://leetcode.com/problems/minimum-sum-of-four-digit-number-after-splitting-digits/discuss/1747018/Python-simple-and-fast-with-explanation-no-permutation
43
You are given a positive integer num consisting of exactly four digits. Split num into two new integers new1 and new2 by using the digits found in num. Leading zeros are allowed in new1 and new2, and all the digits found in num must be used. For example, given num = 2932, you have the following digits: two 2's, one 9 and one 3. Some of the possible pairs [new1, new2] are [22, 93], [23, 92], [223, 9] and [2, 329]. Return the minimum possible sum of new1 and new2. Example 1: Input: num = 2932 Output: 52 Explanation: Some possible pairs [new1, new2] are [29, 23], [223, 9], etc. The minimum sum can be obtained by the pair [29, 23]: 29 + 23 = 52. Example 2: Input: num = 4009 Output: 13 Explanation: Some possible pairs [new1, new2] are [0, 49], [490, 0], etc. The minimum sum can be obtained by the pair [4, 9]: 4 + 9 = 13. Constraints: 1000 <= num <= 9999
Python - simple & fast with explanation - no permutation
4,300
minimum-sum-of-four-digit-number-after-splitting-digits
0.879
fatamorgana
Easy
29,961
2,160
partition array according to given pivot
class Solution: def pivotArray(self, nums: List[int], pivot: int) -> List[int]: ans=[] nums.remove(pivot) i=0 ans.append(pivot) for j in nums: if j<pivot: ans.insert(i,j) i=i+1 elif j==pivot: ans.insert(i+1,j) else: ans.append(j) return ans
https://leetcode.com/problems/partition-array-according-to-given-pivot/discuss/1748566/Python-Simple-and-Clean-Python-Solution-by-Removing-and-Appending
5
You are given a 0-indexed integer array nums and an integer pivot. Rearrange nums such that the following conditions are satisfied: Every element less than pivot appears before every element greater than pivot. Every element equal to pivot appears in between the elements less than and greater than pivot. The relative order of the elements less than pivot and the elements greater than pivot is maintained. More formally, consider every pi, pj where pi is the new position of the ith element and pj is the new position of the jth element. For elements less than pivot, if i < j and nums[i] < pivot and nums[j] < pivot, then pi < pj. Similarly for elements greater than pivot, if i < j and nums[i] > pivot and nums[j] > pivot, then pi < pj. Return nums after the rearrangement. Example 1: Input: nums = [9,12,5,10,14,3,10], pivot = 10 Output: [9,5,3,10,10,12,14] Explanation: The elements 9, 5, and 3 are less than the pivot so they are on the left side of the array. The elements 12 and 14 are greater than the pivot so they are on the right side of the array. The relative ordering of the elements less than and greater than pivot is also maintained. [9, 5, 3] and [12, 14] are the respective orderings. Example 2: Input: nums = [-3,4,3,2], pivot = 2 Output: [-3,2,4,3] Explanation: The element -3 is less than the pivot so it is on the left side of the array. The elements 4 and 3 are greater than the pivot so they are on the right side of the array. The relative ordering of the elements less than and greater than pivot is also maintained. [-3] and [4, 3] are the respective orderings. Constraints: 1 <= nums.length <= 105 -106 <= nums[i] <= 106 pivot equals to an element of nums.
[ Python ] βœ”βœ” Simple and Clean Python Solution by Removing and Appending
475
partition-array-according-to-given-pivot
0.845
ASHOK_KUMAR_MEGHVANSHI
Medium
30,013
2,161
minimum cost to set cooking time
class Solution: def minCostSetTime(self, startAt: int, moveCost: int, pushCost: int, targetSeconds: int) -> int: def count_cost(minutes, seconds): # Calculates cost for certain configuration of minutes and seconds time = f'{minutes // 10}{minutes % 10}{seconds // 10}{seconds % 10}' # mm:ss time = time.lstrip('0') # since 0's are prepended we remove the 0's to the left to minimize cost t = [int(i) for i in time] current = startAt cost = 0 for i in t: if i != current: current = i cost += moveCost cost += pushCost return cost ans = float('inf') for m in range(100): # Check which [mm:ss] configuration works out for s in range(100): if m * 60 + s == targetSeconds: ans = min(ans, count_cost(m, s)) return ans
https://leetcode.com/problems/minimum-cost-to-set-cooking-time/discuss/1746996/Simple-Python-Solution
10
A generic microwave supports cooking times for: at least 1 second. at most 99 minutes and 99 seconds. To set the cooking time, you push at most four digits. The microwave normalizes what you push as four digits by prepending zeroes. It interprets the first two digits as the minutes and the last two digits as the seconds. It then adds them up as the cooking time. For example, You push 9 5 4 (three digits). It is normalized as 0954 and interpreted as 9 minutes and 54 seconds. You push 0 0 0 8 (four digits). It is interpreted as 0 minutes and 8 seconds. You push 8 0 9 0. It is interpreted as 80 minutes and 90 seconds. You push 8 1 3 0. It is interpreted as 81 minutes and 30 seconds. You are given integers startAt, moveCost, pushCost, and targetSeconds. Initially, your finger is on the digit startAt. Moving the finger above any specific digit costs moveCost units of fatigue. Pushing the digit below the finger once costs pushCost units of fatigue. There can be multiple ways to set the microwave to cook for targetSeconds seconds but you are interested in the way with the minimum cost. Return the minimum cost to set targetSeconds seconds of cooking time. Remember that one minute consists of 60 seconds. Example 1: Input: startAt = 1, moveCost = 2, pushCost = 1, targetSeconds = 600 Output: 6 Explanation: The following are the possible ways to set the cooking time. - 1 0 0 0, interpreted as 10 minutes and 0 seconds. The finger is already on digit 1, pushes 1 (with cost 1), moves to 0 (with cost 2), pushes 0 (with cost 1), pushes 0 (with cost 1), and pushes 0 (with cost 1). The cost is: 1 + 2 + 1 + 1 + 1 = 6. This is the minimum cost. - 0 9 6 0, interpreted as 9 minutes and 60 seconds. That is also 600 seconds. The finger moves to 0 (with cost 2), pushes 0 (with cost 1), moves to 9 (with cost 2), pushes 9 (with cost 1), moves to 6 (with cost 2), pushes 6 (with cost 1), moves to 0 (with cost 2), and pushes 0 (with cost 1). The cost is: 2 + 1 + 2 + 1 + 2 + 1 + 2 + 1 = 12. - 9 6 0, normalized as 0960 and interpreted as 9 minutes and 60 seconds. The finger moves to 9 (with cost 2), pushes 9 (with cost 1), moves to 6 (with cost 2), pushes 6 (with cost 1), moves to 0 (with cost 2), and pushes 0 (with cost 1). The cost is: 2 + 1 + 2 + 1 + 2 + 1 = 9. Example 2: Input: startAt = 0, moveCost = 1, pushCost = 2, targetSeconds = 76 Output: 6 Explanation: The optimal way is to push two digits: 7 6, interpreted as 76 seconds. The finger moves to 7 (with cost 1), pushes 7 (with cost 2), moves to 6 (with cost 1), and pushes 6 (with cost 2). The total cost is: 1 + 2 + 1 + 2 = 6 Note other possible ways are 0076, 076, 0116, and 116, but none of them produces the minimum cost. Constraints: 0 <= startAt <= 9 1 <= moveCost, pushCost <= 105 1 <= targetSeconds <= 6039
Simple Python Solution
513
minimum-cost-to-set-cooking-time
0.396
anCoderr
Medium
30,053
2,162
minimum difference in sums after removal of elements
class Solution: def minimumDifference(self, nums: List[int]) -> int: n = len(nums) // 3 # calculate max_sum using min_heap for second part min_heap = nums[(2 * n) :] heapq.heapify(min_heap) max_sum = [0] * (n + 2) max_sum[n + 1] = sum(min_heap) for i in range((2 * n) - 1, n - 1, -1): # push current heapq.heappush(min_heap, nums[i]) # popout minimum from heap val = heapq.heappop(min_heap) # max_sum for this partition max_sum[i - n + 1] = max_sum[i - n + 2] - val + nums[i] # calculate min_sum using max_heap for first part max_heap = [-x for x in nums[:n]] heapq.heapify(max_heap) min_sum = [0] * (n + 2) min_sum[0] = -sum(max_heap) for i in range(n, (2 * n)): # push current heapq.heappush(max_heap, -nums[i]) # popout maximum from heap val = -heapq.heappop(max_heap) # min_sum for this partition min_sum[i - n + 1] = min_sum[i - n] - val + nums[i] # find min difference bw second part (max_sum) and first part (min_sum) ans = math.inf for i in range(0, n + 1): print(i, min_sum[i], max_sum[i]) ans = min((min_sum[i] - max_sum[i + 1]), ans) return ans
https://leetcode.com/problems/minimum-difference-in-sums-after-removal-of-elements/discuss/2392142/Python-solution-or-O(nlogn)-or-explained-with-diagram-or-heap-and-dp-solution
1
You are given a 0-indexed integer array nums consisting of 3 * n elements. You are allowed to remove any subsequence of elements of size exactly n from nums. The remaining 2 * n elements will be divided into two equal parts: The first n elements belonging to the first part and their sum is sumfirst. The next n elements belonging to the second part and their sum is sumsecond. The difference in sums of the two parts is denoted as sumfirst - sumsecond. For example, if sumfirst = 3 and sumsecond = 2, their difference is 1. Similarly, if sumfirst = 2 and sumsecond = 3, their difference is -1. Return the minimum difference possible between the sums of the two parts after the removal of n elements. Example 1: Input: nums = [3,1,2] Output: -1 Explanation: Here, nums has 3 elements, so n = 1. Thus we have to remove 1 element from nums and divide the array into two equal parts. - If we remove nums[0] = 3, the array will be [1,2]. The difference in sums of the two parts will be 1 - 2 = -1. - If we remove nums[1] = 1, the array will be [3,2]. The difference in sums of the two parts will be 3 - 2 = 1. - If we remove nums[2] = 2, the array will be [3,1]. The difference in sums of the two parts will be 3 - 1 = 2. The minimum difference between sums of the two parts is min(-1,1,2) = -1. Example 2: Input: nums = [7,9,5,8,1,3] Output: 1 Explanation: Here n = 2. So we must remove 2 elements and divide the remaining array into two parts containing two elements each. If we remove nums[2] = 5 and nums[3] = 8, the resultant array will be [7,9,1,3]. The difference in sums will be (7+9) - (1+3) = 12. To obtain the minimum difference, we should remove nums[1] = 9 and nums[4] = 1. The resultant array becomes [7,5,8,3]. The difference in sums of the two parts is (7+5) - (8+3) = 1. It can be shown that it is not possible to obtain a difference smaller than 1. Constraints: nums.length == 3 * n 1 <= n <= 105 1 <= nums[i] <= 105
Python solution | O(nlogn) | explained with diagram | heap and dp solution
64
minimum-difference-in-sums-after-removal-of-elements
0.467
wilspi
Hard
30,059
2,163
sort even and odd indices independently
class Solution: def sortEvenOdd(self, nums: List[int]) -> List[int]: n = len(nums) for i in range(0,n,2): for j in range(i+2,n,2): if nums[i] > nums[j]: nums[i],nums[j] = nums[j], nums[i] for i in range(1,n,2): for j in range(i+2,n,2): if nums[i] < nums[j]: nums[i],nums[j] = nums[j], nums[i] return nums
https://leetcode.com/problems/sort-even-and-odd-indices-independently/discuss/2214566/Python-oror-In-Place-Sorting
1
You are given a 0-indexed integer array nums. Rearrange the values of nums according to the following rules: Sort the values at odd indices of nums in non-increasing order. For example, if nums = [4,1,2,3] before this step, it becomes [4,3,2,1] after. The values at odd indices 1 and 3 are sorted in non-increasing order. Sort the values at even indices of nums in non-decreasing order. For example, if nums = [4,1,2,3] before this step, it becomes [2,1,4,3] after. The values at even indices 0 and 2 are sorted in non-decreasing order. Return the array formed after rearranging the values of nums. Example 1: Input: nums = [4,1,2,3] Output: [2,3,4,1] Explanation: First, we sort the values present at odd indices (1 and 3) in non-increasing order. So, nums changes from [4,1,2,3] to [4,3,2,1]. Next, we sort the values present at even indices (0 and 2) in non-decreasing order. So, nums changes from [4,1,2,3] to [2,3,4,1]. Thus, the array formed after rearranging the values is [2,3,4,1]. Example 2: Input: nums = [2,1] Output: [2,1] Explanation: Since there is exactly one odd index and one even index, no rearrangement of values takes place. The resultant array formed is [2,1], which is the same as the initial array. Constraints: 1 <= nums.length <= 100 1 <= nums[i] <= 100
Python || In Place Sorting
186
sort-even-and-odd-indices-independently
0.664
morpheusdurden
Easy
30,062
2,164
smallest value of the rearranged number
class Solution: def smallestNumber(self, num: int) -> int: if num == 0 : return 0 snum = sorted(str(num)) if snum[0] == '-' : return -int("".join(snum[:0:-1])) elif snum[0] == '0' : x = snum.count('0') return "".join([snum[x]]+['0'*x]+snum[x+1:]) else : return "".join(snum)
https://leetcode.com/problems/smallest-value-of-the-rearranged-number/discuss/1755847/PYTHON3-or-EASY-SOLUTION-or
1
You are given an integer num. Rearrange the digits of num such that its value is minimized and it does not contain any leading zeros. Return the rearranged number with minimal value. Note that the sign of the number does not change after rearranging the digits. Example 1: Input: num = 310 Output: 103 Explanation: The possible arrangements for the digits of 310 are 013, 031, 103, 130, 301, 310. The arrangement with the smallest value that does not contain any leading zeros is 103. Example 2: Input: num = -7605 Output: -7650 Explanation: Some possible arrangements for the digits of -7605 are -7650, -6705, -5076, -0567. The arrangement with the smallest value that does not contain any leading zeros is -7650. Constraints: -1015 <= num <= 1015
PYTHON3 | EASY SOLUTION |
108
smallest-value-of-the-rearranged-number
0.513
rohitkhairnar
Medium
30,084
2,165
minimum time to remove all cars containing illegal goods
class Solution: def minimumTime(self, s: str) -> int: ans = inf prefix = 0 for i, ch in enumerate(s): if ch == '1': prefix = min(2 + prefix, i+1) ans = min(ans, prefix + len(s)-1-i) return ans
https://leetcode.com/problems/minimum-time-to-remove-all-cars-containing-illegal-goods/discuss/2465604/Python3-dp
0
You are given a 0-indexed binary string s which represents a sequence of train cars. s[i] = '0' denotes that the ith car does not contain illegal goods and s[i] = '1' denotes that the ith car does contain illegal goods. As the train conductor, you would like to get rid of all the cars containing illegal goods. You can do any of the following three operations any number of times: Remove a train car from the left end (i.e., remove s[0]) which takes 1 unit of time. Remove a train car from the right end (i.e., remove s[s.length - 1]) which takes 1 unit of time. Remove a train car from anywhere in the sequence which takes 2 units of time. Return the minimum time to remove all the cars containing illegal goods. Note that an empty sequence of cars is considered to have no cars containing illegal goods. Example 1: Input: s = "1100101" Output: 5 Explanation: One way to remove all the cars containing illegal goods from the sequence is to - remove a car from the left end 2 times. Time taken is 2 * 1 = 2. - remove a car from the right end. Time taken is 1. - remove the car containing illegal goods found in the middle. Time taken is 2. This obtains a total time of 2 + 1 + 2 = 5. An alternative way is to - remove a car from the left end 2 times. Time taken is 2 * 1 = 2. - remove a car from the right end 3 times. Time taken is 3 * 1 = 3. This also obtains a total time of 2 + 3 = 5. 5 is the minimum time taken to remove all the cars containing illegal goods. There are no other ways to remove them with less time. Example 2: Input: s = "0010" Output: 2 Explanation: One way to remove all the cars containing illegal goods from the sequence is to - remove a car from the left end 3 times. Time taken is 3 * 1 = 3. This obtains a total time of 3. Another way to remove all the cars containing illegal goods from the sequence is to - remove the car containing illegal goods found in the middle. Time taken is 2. This obtains a total time of 2. Another way to remove all the cars containing illegal goods from the sequence is to - remove a car from the right end 2 times. Time taken is 2 * 1 = 2. This obtains a total time of 2. 2 is the minimum time taken to remove all the cars containing illegal goods. There are no other ways to remove them with less time. Constraints: 1 <= s.length <= 2 * 105 s[i] is either '0' or '1'.
[Python3] dp
24
minimum-time-to-remove-all-cars-containing-illegal-goods
0.402
ye15
Hard
30,094
2,167
count operations to obtain zero
class Solution: def countOperations(self, num1: int, num2: int) -> int: ans = 0 while num1 and num2: ans += num1//num2 num1, num2 = num2, num1%num2 return ans
https://leetcode.com/problems/count-operations-to-obtain-zero/discuss/1766882/Python3-simulation
4
You are given two non-negative integers num1 and num2. In one operation, if num1 >= num2, you must subtract num2 from num1, otherwise subtract num1 from num2. For example, if num1 = 5 and num2 = 4, subtract num2 from num1, thus obtaining num1 = 1 and num2 = 4. However, if num1 = 4 and num2 = 5, after one operation, num1 = 4 and num2 = 1. Return the number of operations required to make either num1 = 0 or num2 = 0. Example 1: Input: num1 = 2, num2 = 3 Output: 3 Explanation: - Operation 1: num1 = 2, num2 = 3. Since num1 < num2, we subtract num1 from num2 and get num1 = 2, num2 = 3 - 2 = 1. - Operation 2: num1 = 2, num2 = 1. Since num1 > num2, we subtract num2 from num1. - Operation 3: num1 = 1, num2 = 1. Since num1 == num2, we subtract num2 from num1. Now num1 = 0 and num2 = 1. Since num1 == 0, we do not need to perform any further operations. So the total number of operations required is 3. Example 2: Input: num1 = 10, num2 = 10 Output: 1 Explanation: - Operation 1: num1 = 10, num2 = 10. Since num1 == num2, we subtract num2 from num1 and get num1 = 10 - 10 = 0. Now num1 = 0 and num2 = 10. Since num1 == 0, we are done. So the total number of operations required is 1. Constraints: 0 <= num1, num2 <= 105
[Python3] simulation
385
count-operations-to-obtain-zero
0.755
ye15
Easy
30,096
2,169
minimum operations to make the array alternating
class Solution: def minimumOperations(self, nums: List[int]) -> int: pad = lambda x: x + [(None, 0)]*(2-len(x)) even = pad(Counter(nums[::2]).most_common(2)) odd = pad(Counter(nums[1::2]).most_common(2)) return len(nums) - (max(even[0][1] + odd[1][1], even[1][1] + odd[0][1]) if even[0][0] == odd[0][0] else even[0][1] + odd[0][1])
https://leetcode.com/problems/minimum-operations-to-make-the-array-alternating/discuss/1766909/Python3-4-line
19
You are given a 0-indexed array nums consisting of n positive integers. The array nums is called alternating if: nums[i - 2] == nums[i], where 2 <= i <= n - 1. nums[i - 1] != nums[i], where 1 <= i <= n - 1. In one operation, you can choose an index i and change nums[i] into any positive integer. Return the minimum number of operations required to make the array alternating. Example 1: Input: nums = [3,1,3,2,4,3] Output: 3 Explanation: One way to make the array alternating is by converting it to [3,1,3,1,3,1]. The number of operations required in this case is 3. It can be proven that it is not possible to make the array alternating in less than 3 operations. Example 2: Input: nums = [1,2,2,2,2] Output: 2 Explanation: One way to make the array alternating is by converting it to [1,2,1,2,1]. The number of operations required in this case is 2. Note that the array cannot be converted to [2,2,2,2,2] because in this case nums[0] == nums[1] which violates the conditions of an alternating array. Constraints: 1 <= nums.length <= 105 1 <= nums[i] <= 105
[Python3] 4-line
1,600
minimum-operations-to-make-the-array-alternating
0.332
ye15
Medium
30,123
2,170
removing minimum number of magic beans
class Solution: def minimumRemoval(self, beans: List[int]) -> int: beans.sort() return sum(beans) - max((len(beans)-i)*x for i, x in enumerate(beans))
https://leetcode.com/problems/removing-minimum-number-of-magic-beans/discuss/1766873/Python3-2-line
4
You are given an array of positive integers beans, where each integer represents the number of magic beans found in a particular magic bag. Remove any number of beans (possibly none) from each bag such that the number of beans in each remaining non-empty bag (still containing at least one bean) is equal. Once a bean has been removed from a bag, you are not allowed to return it to any of the bags. Return the minimum number of magic beans that you have to remove. Example 1: Input: beans = [4,1,6,5] Output: 4 Explanation: - We remove 1 bean from the bag with only 1 bean. This results in the remaining bags: [4,0,6,5] - Then we remove 2 beans from the bag with 6 beans. This results in the remaining bags: [4,0,4,5] - Then we remove 1 bean from the bag with 5 beans. This results in the remaining bags: [4,0,4,4] We removed a total of 1 + 2 + 1 = 4 beans to make the remaining non-empty bags have an equal number of beans. There are no other solutions that remove 4 beans or fewer. Example 2: Input: beans = [2,10,3,2] Output: 7 Explanation: - We remove 2 beans from one of the bags with 2 beans. This results in the remaining bags: [0,10,3,2] - Then we remove 2 beans from the other bag with 2 beans. This results in the remaining bags: [0,10,3,0] - Then we remove 3 beans from the bag with 3 beans. This results in the remaining bags: [0,10,0,0] We removed a total of 2 + 2 + 3 = 7 beans to make the remaining non-empty bags have an equal number of beans. There are no other solutions that removes 7 beans or fewer. Constraints: 1 <= beans.length <= 105 1 <= beans[i] <= 105
[Python3] 2-line
163
removing-minimum-number-of-magic-beans
0.42
ye15
Medium
30,138
2,171
maximum and sum of array
class Solution: def maximumANDSum(self, nums: List[int], numSlots: int) -> int: @cache def fn(k, m): """Return max AND sum.""" if k == len(nums): return 0 ans = 0 for i in range(numSlots): if m &amp; 1<<2*i == 0 or m &amp; 1<<2*i+1 == 0: if m &amp; 1<<2*i == 0: mm = m ^ 1<<2*i else: mm = m ^ 1<<2*i+1 ans = max(ans, (nums[k] &amp; i+1) + fn(k+1, mm)) return ans return fn(0, 0)
https://leetcode.com/problems/maximum-and-sum-of-array/discuss/1766984/Python3-dp-(top-down)
13
You are given an integer array nums of length n and an integer numSlots such that 2 * numSlots >= n. There are numSlots slots numbered from 1 to numSlots. You have to place all n integers into the slots such that each slot contains at most two numbers. The AND sum of a given placement is the sum of the bitwise AND of every number with its respective slot number. For example, the AND sum of placing the numbers [1, 3] into slot 1 and [4, 6] into slot 2 is equal to (1 AND 1) + (3 AND 1) + (4 AND 2) + (6 AND 2) = 1 + 1 + 0 + 2 = 4. Return the maximum possible AND sum of nums given numSlots slots. Example 1: Input: nums = [1,2,3,4,5,6], numSlots = 3 Output: 9 Explanation: One possible placement is [1, 4] into slot 1, [2, 6] into slot 2, and [3, 5] into slot 3. This gives the maximum AND sum of (1 AND 1) + (4 AND 1) + (2 AND 2) + (6 AND 2) + (3 AND 3) + (5 AND 3) = 1 + 0 + 2 + 2 + 3 + 1 = 9. Example 2: Input: nums = [1,3,10,4,7,1], numSlots = 9 Output: 24 Explanation: One possible placement is [1, 1] into slot 1, [3] into slot 3, [4] into slot 4, [7] into slot 7, and [10] into slot 9. This gives the maximum AND sum of (1 AND 1) + (1 AND 1) + (3 AND 3) + (4 AND 4) + (7 AND 7) + (10 AND 9) = 1 + 1 + 3 + 4 + 7 + 8 = 24. Note that slots 2, 5, 6, and 8 are empty which is permitted. Constraints: n == nums.length 1 <= numSlots <= 9 1 <= n <= 2 * numSlots 1 <= nums[i] <= 15
[Python3] dp (top-down)
591
maximum-and-sum-of-array
0.475
ye15
Hard
30,149
2,172
count equal and divisible pairs in an array
class Solution: def countPairs(self, nums: List[int], k: int) -> int: n=len(nums) c=0 for i in range(0,n): for j in range(i+1,n): if nums[i]==nums[j] and ((i*j)%k==0): c+=1 return c
https://leetcode.com/problems/count-equal-and-divisible-pairs-in-an-array/discuss/1783447/Python3-Solution-fastest
6
Given a 0-indexed integer array nums of length n and an integer k, return the number of pairs (i, j) where 0 <= i < j < n, such that nums[i] == nums[j] and (i * j) is divisible by k. Example 1: Input: nums = [3,1,2,2,2,1,3], k = 2 Output: 4 Explanation: There are 4 pairs that meet all the requirements: - nums[0] == nums[6], and 0 * 6 == 0, which is divisible by 2. - nums[2] == nums[3], and 2 * 3 == 6, which is divisible by 2. - nums[2] == nums[4], and 2 * 4 == 8, which is divisible by 2. - nums[3] == nums[4], and 3 * 4 == 12, which is divisible by 2. Example 2: Input: nums = [1,2,3,4], k = 1 Output: 0 Explanation: Since no value in nums is repeated, there are no pairs (i,j) that meet all the requirements. Constraints: 1 <= nums.length <= 100 1 <= nums[i], k <= 100
Python3 Solution fastest
812
count-equal-and-divisible-pairs-in-an-array
0.803
Anilchouhan181
Easy
30,151
2,176
find three consecutive integers that sum to a given number
class Solution: def sumOfThree(self, num: int) -> List[int]: return [] if num % 3 else [num//3-1, num//3, num//3+1]
https://leetcode.com/problems/find-three-consecutive-integers-that-sum-to-a-given-number/discuss/1783425/Python3-1-line
5
Given an integer num, return three consecutive integers (as a sorted array) that sum to num. If num cannot be expressed as the sum of three consecutive integers, return an empty array. Example 1: Input: num = 33 Output: [10,11,12] Explanation: 33 can be expressed as 10 + 11 + 12 = 33. 10, 11, 12 are 3 consecutive integers, so we return [10, 11, 12]. Example 2: Input: num = 4 Output: [] Explanation: There is no way to express 4 as the sum of 3 consecutive integers. Constraints: 0 <= num <= 1015
[Python3] 1-line
258
find-three-consecutive-integers-that-sum-to-a-given-number
0.637
ye15
Medium
30,184
2,177
maximum split of positive even integers
class Solution: def maximumEvenSplit(self, finalSum: int) -> List[int]: l=set() if finalSum%2!=0: return l else: s=0 i=2 # even pointer 2, 4, 6, 8, 10, 12........... while(s<finalSum): s+=i #sum l.add(i) # append the i in list i+=2 if s==finalSum: #if sum s is equal to finalSum then no modidfication required return l else: l.discard(s-finalSum) #Deleting the element which makes s greater than finalSum return l
https://leetcode.com/problems/maximum-split-of-positive-even-integers/discuss/1783966/Simple-Python-Solution-with-Explanation-oror-O(sqrt(n))-Time-Complexity-oror-O(1)-Space-Complexity
51
You are given an integer finalSum. Split it into a sum of a maximum number of unique positive even integers. For example, given finalSum = 12, the following splits are valid (unique positive even integers summing up to finalSum): (12), (2 + 10), (2 + 4 + 6), and (4 + 8). Among them, (2 + 4 + 6) contains the maximum number of integers. Note that finalSum cannot be split into (2 + 2 + 4 + 4) as all the numbers should be unique. Return a list of integers that represent a valid split containing a maximum number of integers. If no valid split exists for finalSum, return an empty list. You may return the integers in any order. Example 1: Input: finalSum = 12 Output: [2,4,6] Explanation: The following are valid splits: (12), (2 + 10), (2 + 4 + 6), and (4 + 8). (2 + 4 + 6) has the maximum number of integers, which is 3. Thus, we return [2,4,6]. Note that [2,6,4], [6,2,4], etc. are also accepted. Example 2: Input: finalSum = 7 Output: [] Explanation: There are no valid splits for the given finalSum. Thus, we return an empty array. Example 3: Input: finalSum = 28 Output: [6,8,2,12] Explanation: The following are valid splits: (2 + 26), (6 + 8 + 2 + 12), and (4 + 24). (6 + 8 + 2 + 12) has the maximum number of integers, which is 4. Thus, we return [6,8,2,12]. Note that [10,2,4,12], [6,2,4,16], etc. are also accepted. Constraints: 1 <= finalSum <= 1010
Simple Python Solution with Explanation || O(sqrt(n)) Time Complexity || O(1) Space Complexity
2,000
maximum-split-of-positive-even-integers
0.591
HimanshuGupta_p1
Medium
30,208
2,178
count good triplets in an array
class Solution: def goodTriplets(self, nums1: List[int], nums2: List[int]) -> int: n = len(nums1) hashmap2 = {} for i in range(n): hashmap2[nums2[i]] = i indices = [] for num in nums1: indices.append(hashmap2[num]) from sortedcontainers import SortedList left, right = SortedList(), SortedList() leftCount, rightCount = [], [] for i in range(n): leftCount.append(left.bisect_left(indices[i])) left.add(indices[i]) for i in range(n - 1, -1, -1): rightCount.append(len(right) - right.bisect_right(indices[i])) right.add(indices[i]) count = 0 for i in range(n): count += leftCount[i] * rightCount[n - 1 - i] return count
https://leetcode.com/problems/count-good-triplets-in-an-array/discuss/1783361/Python-3-SortedList-solution-O(NlogN)
13
You are given two 0-indexed arrays nums1 and nums2 of length n, both of which are permutations of [0, 1, ..., n - 1]. A good triplet is a set of 3 distinct values which are present in increasing order by position both in nums1 and nums2. In other words, if we consider pos1v as the index of the value v in nums1 and pos2v as the index of the value v in nums2, then a good triplet will be a set (x, y, z) where 0 <= x, y, z <= n - 1, such that pos1x < pos1y < pos1z and pos2x < pos2y < pos2z. Return the total number of good triplets. Example 1: Input: nums1 = [2,0,1,3], nums2 = [0,1,2,3] Output: 1 Explanation: There are 4 triplets (x,y,z) such that pos1x < pos1y < pos1z. They are (2,0,1), (2,0,3), (2,1,3), and (0,1,3). Out of those triplets, only the triplet (0,1,3) satisfies pos2x < pos2y < pos2z. Hence, there is only 1 good triplet. Example 2: Input: nums1 = [4,0,1,3,2], nums2 = [4,1,0,2,3] Output: 4 Explanation: The 4 good triplets are (4,0,3), (4,0,2), (4,1,3), and (4,1,2). Constraints: n == nums1.length == nums2.length 3 <= n <= 105 0 <= nums1[i], nums2[i] <= n - 1 nums1 and nums2 are permutations of [0, 1, ..., n - 1].
Python 3 SortedList solution, O(NlogN)
554
count-good-triplets-in-an-array
0.371
xil899
Hard
30,226
2,179
count integers with even digit sum
class Solution: def countEven(self, num: int) -> int: return num // 2 if sum([int(k) for k in str(num)]) % 2 == 0 else (num - 1) // 2
https://leetcode.com/problems/count-integers-with-even-digit-sum/discuss/1785049/lessPython3greater-O(1)-Discrete-Formula-100-faster-1-LINE
9
Given a positive integer num, return the number of positive integers less than or equal to num whose digit sums are even. The digit sum of a positive integer is the sum of all its digits. Example 1: Input: num = 4 Output: 2 Explanation: The only integers less than or equal to 4 whose digit sums are even are 2 and 4. Example 2: Input: num = 30 Output: 14 Explanation: The 14 integers less than or equal to 30 whose digit sums are even are 2, 4, 6, 8, 11, 13, 15, 17, 19, 20, 22, 24, 26, and 28. Constraints: 1 <= num <= 1000
<Python3> O(1) - Discrete Formula - 100% faster - 1 LINE
845
count-integers-with-even-digit-sum
0.645
drknzz
Easy
30,229
2,180
merge nodes in between zeros
class Solution: def mergeNodes(self, head: Optional[ListNode]) -> Optional[ListNode]: d=ListNode(0) t=0 r=ListNode(0,d) while head: if head.val!=0: t+=head.val else: print(t) if t!=0: d.next=ListNode(t) d=d.next t=0 head=head.next return r.next.next
https://leetcode.com/problems/merge-nodes-in-between-zeros/discuss/1784873/Python-3-or-Dummy-Node-O(N)-Time-Solution
6
You are given the head of a linked list, which contains a series of integers separated by 0's. The beginning and end of the linked list will have Node.val == 0. For every two consecutive 0's, merge all the nodes lying in between them into a single node whose value is the sum of all the merged nodes. The modified list should not contain any 0's. Return the head of the modified linked list. Example 1: Input: head = [0,3,1,0,4,5,2,0] Output: [4,11] Explanation: The above figure represents the given linked list. The modified list contains - The sum of the nodes marked in green: 3 + 1 = 4. - The sum of the nodes marked in red: 4 + 5 + 2 = 11. Example 2: Input: head = [0,1,0,3,0,2,2,0] Output: [1,3,4] Explanation: The above figure represents the given linked list. The modified list contains - The sum of the nodes marked in green: 1 = 1. - The sum of the nodes marked in red: 3 = 3. - The sum of the nodes marked in yellow: 2 + 2 = 4. Constraints: The number of nodes in the list is in the range [3, 2 * 105]. 0 <= Node.val <= 1000 There are no two consecutive nodes with Node.val == 0. The beginning and end of the linked list have Node.val == 0.
Python 3 | Dummy Node O(N) Time Solution
576
merge-nodes-in-between-zeros
0.867
MrShobhit
Medium
30,271
2,181
construct string with repeat limit
class Solution: def repeatLimitedString(self, s: str, repeatLimit: int) -> str: pq = [(-ord(k), v) for k, v in Counter(s).items()] heapify(pq) ans = [] while pq: k, v = heappop(pq) if ans and ans[-1] == k: if not pq: break kk, vv = heappop(pq) ans.append(kk) if vv-1: heappush(pq, (kk, vv-1)) heappush(pq, (k, v)) else: m = min(v, repeatLimit) ans.extend([k]*m) if v-m: heappush(pq, (k, v-m)) return "".join(chr(-x) for x in ans)
https://leetcode.com/problems/construct-string-with-repeat-limit/discuss/1784789/Python3-priority-queue
23
You are given a string s and an integer repeatLimit. Construct a new string repeatLimitedString using the characters of s such that no letter appears more than repeatLimit times in a row. You do not have to use all characters from s. Return the lexicographically largest repeatLimitedString possible. A string a is lexicographically larger than a string b if in the first position where a and b differ, string a has a letter that appears later in the alphabet than the corresponding letter in b. If the first min(a.length, b.length) characters do not differ, then the longer string is the lexicographically larger one. Example 1: Input: s = "cczazcc", repeatLimit = 3 Output: "zzcccac" Explanation: We use all of the characters from s to construct the repeatLimitedString "zzcccac". The letter 'a' appears at most 1 time in a row. The letter 'c' appears at most 3 times in a row. The letter 'z' appears at most 2 times in a row. Hence, no letter appears more than repeatLimit times in a row and the string is a valid repeatLimitedString. The string is the lexicographically largest repeatLimitedString possible so we return "zzcccac". Note that the string "zzcccca" is lexicographically larger but the letter 'c' appears more than 3 times in a row, so it is not a valid repeatLimitedString. Example 2: Input: s = "aababab", repeatLimit = 2 Output: "bbabaa" Explanation: We use only some of the characters from s to construct the repeatLimitedString "bbabaa". The letter 'a' appears at most 2 times in a row. The letter 'b' appears at most 2 times in a row. Hence, no letter appears more than repeatLimit times in a row and the string is a valid repeatLimitedString. The string is the lexicographically largest repeatLimitedString possible so we return "bbabaa". Note that the string "bbabaaa" is lexicographically larger but the letter 'a' appears more than 2 times in a row, so it is not a valid repeatLimitedString. Constraints: 1 <= repeatLimit <= s.length <= 105 s consists of lowercase English letters.
[Python3] priority queue
1,100
construct-string-with-repeat-limit
0.519
ye15
Medium
30,294
2,182