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
elimination game
class Solution: def lastRemaining(self, n: int) -> int: if n == 1: return 1 if n&1: n -= 1 return n + 2 - 2*self.lastRemaining(n//2)
https://leetcode.com/problems/elimination-game/discuss/824126/Python3-3-line-O(logN)
5
You have a list arr of all integers in the range [1, n] sorted in a strictly increasing order. Apply the following algorithm on arr: Starting from left to right, remove the first number and every other number afterward until you reach the end of the list. Repeat the previous step again, but this time from right to left, remove the rightmost number and every other number from the remaining numbers. Keep repeating the steps again, alternating left to right and right to left, until a single number remains. Given the integer n, return the last number that remains in arr. Example 1: Input: n = 9 Output: 6 Explanation: arr = [1, 2, 3, 4, 5, 6, 7, 8, 9] arr = [2, 4, 6, 8] arr = [2, 6] arr = [6] Example 2: Input: n = 1 Output: 1 Constraints: 1 <= n <= 109
[Python3] 3-line O(logN)
588
elimination-game
0.465
ye15
Medium
6,739
390
perfect rectangle
class Solution: def isRectangleCover(self, rectangles: List[List[int]]) -> bool: area = 0 corners = set() a = lambda: (Y-y) * (X-x) for x, y, X, Y in rectangles: area += a() corners ^= {(x,y), (x,Y), (X,y), (X,Y)} if len(corners) != 4: return False x, y = min(corners, key=lambda x: x[0] + x[1]) X, Y = max(corners, key=lambda x: x[0] + x[1]) return a() == area
https://leetcode.com/problems/perfect-rectangle/discuss/968076/Python-Fast-and-clear-solution-with-explanation
40
Given an array rectangles where rectangles[i] = [xi, yi, ai, bi] represents an axis-aligned rectangle. The bottom-left point of the rectangle is (xi, yi) and the top-right point of it is (ai, bi). Return true if all the rectangles together form an exact cover of a rectangular region. Example 1: Input: rectangles = [[1,1,3,3],[3,1,4,2],[3,2,4,4],[1,3,2,4],[2,3,3,4]] Output: true Explanation: All 5 rectangles together form an exact cover of a rectangular region. Example 2: Input: rectangles = [[1,1,2,3],[1,3,2,4],[3,1,4,2],[3,2,4,4]] Output: false Explanation: Because there is a gap between the two rectangular regions. Example 3: Input: rectangles = [[1,1,3,3],[3,1,4,2],[1,3,2,4],[2,2,4,4]] Output: false Explanation: Because two of the rectangles overlap with each other. Constraints: 1 <= rectangles.length <= 2 * 104 rectangles[i].length == 4 -105 <= xi, yi, ai, bi <= 105
[Python] Fast and clear solution with explanation
1,200
perfect-rectangle
0.325
modusV
Hard
6,748
391
is subsequence
class Solution(object): def isSubsequence(self, s, t): # Base case if not s: return True i = 0 # Traverse elements of t string for j in t: # If this index matches to the index of s string, increment i pointer... if j == s[i]: i += 1 # If the pointer is equal to the size of s... if i == len(s): break return i == len(s)
https://leetcode.com/problems/is-subsequence/discuss/2473010/Very-Easy-oror-100-oror-Fully-Explained-oror-Java-C%2B%2B-Python-JS-C-Python3-(Two-Pointers-Approach)
16
Given two strings s and t, return true if s is a subsequence of t, or false otherwise. A subsequence of a string is a new string that is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (i.e., "ace" is a subsequence of "abcde" while "aec" is not). Example 1: Input: s = "abc", t = "ahbgdc" Output: true Example 2: Input: s = "axc", t = "ahbgdc" Output: false Constraints: 0 <= s.length <= 100 0 <= t.length <= 104 s and t consist only of lowercase English letters. Follow up: Suppose there are lots of incoming s, say s1, s2, ..., sk where k >= 109, and you want to check one by one to see if t has its subsequence. In this scenario, how would you change your code?
Very Easy || 100% || Fully Explained || Java, C++, Python, JS, C, Python3 (Two-Pointers Approach)
998
is-subsequence
0.49
PratikSen07
Easy
6,752
392
utf 8 validation
class Solution: def validUtf8(self, data: List[int]) -> bool: n = len(data) l = [2**i for i in range(7, -1, -1)] def isXByteSeq(pos, X): f = data[pos] rem = data[pos+1:pos+X] ret = (f&amp;l[X]) == 0 for i in range(X): ret &amp;= (f&amp;l[i]) != 0 for num in rem: ret &amp;= (num&amp;l[0]) != 0 ret &amp;= (num&amp;l[1]) == 0 return ret @cache def res(pos = 0): ret = False if pos == n: ret = True if pos + 3 < n: ret |= isXByteSeq(pos, 4) and res(pos + 4) if pos + 2 < n: ret |= isXByteSeq(pos, 3) and res(pos + 3) if pos + 1 < n: ret |= isXByteSeq(pos, 2) and res(pos + 2) if pos < n: ret |= isXByteSeq(pos, 0) and res(pos + 1) return ret return res()
https://leetcode.com/problems/utf-8-validation/discuss/2568848/Python3-or-DP-or-Memoization-or-Neat-Solution-or-O(n)
4
Given an integer array data representing the data, return whether it is a valid UTF-8 encoding (i.e. it translates to a sequence of valid UTF-8 encoded characters). A character in UTF8 can be from 1 to 4 bytes long, subjected to the following rules: For a 1-byte character, the first bit is a 0, followed by its Unicode code. For an n-bytes character, the first n bits are all one's, the n + 1 bit is 0, followed by n - 1 bytes with the most significant 2 bits being 10. This is how the UTF-8 encoding would work: Number of Bytes | UTF-8 Octet Sequence | (binary) --------------------+----------------------------------------- 1 | 0xxxxxxx 2 | 110xxxxx 10xxxxxx 3 | 1110xxxx 10xxxxxx 10xxxxxx 4 | 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx x denotes a bit in the binary form of a byte that may be either 0 or 1. Note: The input is an array of integers. Only the least significant 8 bits of each integer is used to store the data. This means each integer represents only 1 byte of data. Example 1: Input: data = [197,130,1] Output: true Explanation: data represents the octet sequence: 11000101 10000010 00000001. It is a valid utf-8 encoding for a 2-bytes character followed by a 1-byte character. Example 2: Input: data = [235,140,4] Output: false Explanation: data represented the octet sequence: 11101011 10001100 00000100. The first 3 bits are all one's and the 4th bit is 0 means it is a 3-bytes character. The next byte is a continuation byte which starts with 10 and that's correct. But the second continuation byte does not start with 10, so it is invalid. Constraints: 1 <= data.length <= 2 * 104 0 <= data[i] <= 255
Python3 | DP | Memoization | Neat Solution | O(n)
497
utf-8-validation
0.452
DheerajGadwala
Medium
6,807
393
decode string
class Solution: def decodeString(self, s: str) -> str: res,num = "",0 st = [] for c in s: if c.isdigit(): num = num*10+int(c) elif c=="[": st.append(res) st.append(num) res="" num=0 elif c=="]": pnum = st.pop() pstr = st.pop() res = pstr + pnum*res else: res+=c return res
https://leetcode.com/problems/decode-string/discuss/1400105/98-faster-oror-With-and-without-Stack-oror-Cleane-and-Concise
27
Given an encoded string, return its decoded string. The encoding rule is: k[encoded_string], where the encoded_string inside the square brackets is being repeated exactly k times. Note that k is guaranteed to be a positive integer. You may assume that the input string is always valid; there are no extra white spaces, square brackets are well-formed, etc. Furthermore, you may assume that the original data does not contain any digits and that digits are only for those repeat numbers, k. For example, there will not be input like 3a or 2[4]. The test cases are generated so that the length of the output will never exceed 105. Example 1: Input: s = "3[a]2[bc]" Output: "aaabcbc" Example 2: Input: s = "3[a2[c]]" Output: "accaccacc" Example 3: Input: s = "2[abc]3[cd]ef" Output: "abcabccdcdcdef" Constraints: 1 <= s.length <= 30 s consists of lowercase English letters, digits, and square brackets '[]'. s is guaranteed to be a valid input. All the integers in s are in the range [1, 300].
🐍 98% faster || With and without Stack || Cleane & Concise 📌📌
2,700
decode-string
0.576
abhi9Rai
Medium
6,831
394
longest substring with at least k repeating characters
class Solution: def rec(self, s, k): c = Counter(s) if pattern := "|".join(filter(lambda x: c[x] < k, c)): if arr := list(filter(lambda x: len(x) >= k, re.split(pattern, s))): return max(map(lambda x: self.rec(x, k), arr)) return 0 return len(s) def longestSubstring(self, s: str, k: int) -> int: return self.rec(s, k)
https://leetcode.com/problems/longest-substring-with-at-least-k-repeating-characters/discuss/1721267/Faster-than-97.6.-Recursion
3
Given a string s and an integer k, return the length of the longest substring of s such that the frequency of each character in this substring is greater than or equal to k. if no such substring exists, return 0. Example 1: Input: s = "aaabb", k = 3 Output: 3 Explanation: The longest substring is "aaa", as 'a' is repeated 3 times. Example 2: Input: s = "ababbc", k = 2 Output: 5 Explanation: The longest substring is "ababb", as 'a' is repeated 2 times and 'b' is repeated 3 times. Constraints: 1 <= s.length <= 104 s consists of only lowercase English letters. 1 <= k <= 105
Faster than 97.6%. Recursion
244
longest-substring-with-at-least-k-repeating-characters
0.448
mygurbanov
Medium
6,877
395
rotate function
class Solution: def maxRotateFunction(self, A: List[int]) -> int: s, n = sum(A), len(A) cur_sum = sum([i*j for i, j in enumerate(A)]) ans = cur_sum for i in range(n): ans = max(ans, cur_sum := cur_sum + s-A[n-1-i]*n) return ans
https://leetcode.com/problems/rotate-function/discuss/857056/Python-3-(Py3.8)-or-Math-O(n)-or-Explanation
6
You are given an integer array nums of length n. Assume arrk to be an array obtained by rotating nums by k positions clock-wise. We define the rotation function F on nums as follow: F(k) = 0 * arrk[0] + 1 * arrk[1] + ... + (n - 1) * arrk[n - 1]. Return the maximum value of F(0), F(1), ..., F(n-1). The test cases are generated so that the answer fits in a 32-bit integer. Example 1: Input: nums = [4,3,2,6] Output: 26 Explanation: F(0) = (0 * 4) + (1 * 3) + (2 * 2) + (3 * 6) = 0 + 3 + 4 + 18 = 25 F(1) = (0 * 6) + (1 * 4) + (2 * 3) + (3 * 2) = 0 + 4 + 6 + 6 = 16 F(2) = (0 * 2) + (1 * 6) + (2 * 4) + (3 * 3) = 0 + 6 + 8 + 9 = 23 F(3) = (0 * 3) + (1 * 2) + (2 * 6) + (3 * 4) = 0 + 2 + 12 + 12 = 26 So the maximum value of F(0), F(1), F(2), F(3) is F(3) = 26. Example 2: Input: nums = [100] Output: 0 Constraints: n == nums.length 1 <= n <= 105 -100 <= nums[i] <= 100
Python 3 (Py3.8) | Math, O(n) | Explanation
588
rotate-function
0.404
idontknoooo
Medium
6,894
396
integer replacement
class Solution: def integerReplacement(self, n: int) -> int: cnt = 0 while n != 1: if n%2 == 0: n//=2 elif n%4 == 1 or n == 3: n -= 1 else: n += 1 cnt += 1 return cnt
https://leetcode.com/problems/integer-replacement/discuss/663134/Two-solution-in-Python
4
Given a positive integer n, you can apply one of the following operations: If n is even, replace n with n / 2. If n is odd, replace n with either n + 1 or n - 1. Return the minimum number of operations needed for n to become 1. Example 1: Input: n = 8 Output: 3 Explanation: 8 -> 4 -> 2 -> 1 Example 2: Input: n = 7 Output: 4 Explanation: 7 -> 8 -> 4 -> 2 -> 1 or 7 -> 6 -> 3 -> 2 -> 1 Example 3: Input: n = 4 Output: 2 Constraints: 1 <= n <= 231 - 1
Two solution in Python
351
integer-replacement
0.352
realslimshady
Medium
6,902
397
random pick index
class Solution: def __init__(self, nums: List[int]): # Reservoir Sampling (which can handle the linked list with unknown size), time complexity O(n) (init: O(1), pick: O(n)), space complextiy O(1) self.nums = nums def pick(self, target: int) -> int: # https://docs.python.org/3/library/random.html count = 0 chosen_index = None for i in range(len(self.nums)): if self.nums[i] != target: continue count += 1 if count == 1: chosen_index = i elif random.random() < 1 / count: chosen_index = i return chosen_index
https://leetcode.com/problems/random-pick-index/discuss/1671979/Python-3-Reservoir-Sampling-O(n)-Time-and-O(1)-Space
6
Given an integer array nums with possible duplicates, randomly output the index of a given target number. You can assume that the given target number must exist in the array. Implement the Solution class: Solution(int[] nums) Initializes the object with the array nums. int pick(int target) Picks a random index i from nums where nums[i] == target. If there are multiple valid i's, then each index should have an equal probability of returning. Example 1: Input ["Solution", "pick", "pick", "pick"] [[[1, 2, 3, 3, 3]], [3], [1], [3]] Output [null, 4, 0, 2] Explanation Solution solution = new Solution([1, 2, 3, 3, 3]); solution.pick(3); // It should return either index 2, 3, or 4 randomly. Each index should have equal probability of returning. solution.pick(1); // It should return 0. Since in the array only nums[0] is equal to 1. solution.pick(3); // It should return either index 2, 3, or 4 randomly. Each index should have equal probability of returning. Constraints: 1 <= nums.length <= 2 * 104 -231 <= nums[i] <= 231 - 1 target is an integer from nums. At most 104 calls will be made to pick.
Python 3 Reservoir Sampling, O(n) Time & O(1) Space
453
random-pick-index
0.628
xil899
Medium
6,922
398
evaluate division
class Solution: def calcEquation(self, equations: List[List[str]], values: List[float], queries: List[List[str]]) -> List[float]: graph = {} for (u, v), w in zip(equations, values): graph.setdefault(u, []).append((v, 1/w)) graph.setdefault(v, []).append((u, w)) def dfs(n, g, val=1): """Depth-first traverse the graph.""" if n in vals: return vals[n] = val, g for nn, w in graph.get(n, []): dfs(nn, g, w*val) vals = dict() for i, n in enumerate(graph): dfs(n, i) ans = [] for u, v in queries: if u in vals and v in vals and vals[u][1] == vals[v][1]: ans.append(vals[u][0]/vals[v][0]) else: ans.append(-1) return ans
https://leetcode.com/problems/evaluate-division/discuss/827506/Python3-dfs-and-union-find
8
You are given an array of variable pairs equations and an array of real numbers values, where equations[i] = [Ai, Bi] and values[i] represent the equation Ai / Bi = values[i]. Each Ai or Bi is a string that represents a single variable. You are also given some queries, where queries[j] = [Cj, Dj] represents the jth query where you must find the answer for Cj / Dj = ?. Return the answers to all queries. If a single answer cannot be determined, return -1.0. Note: The input is always valid. You may assume that evaluating the queries will not result in division by zero and that there is no contradiction. Note: The variables that do not occur in the list of equations are undefined, so the answer cannot be determined for them. Example 1: Input: equations = [["a","b"],["b","c"]], values = [2.0,3.0], queries = [["a","c"],["b","a"],["a","e"],["a","a"],["x","x"]] Output: [6.00000,0.50000,-1.00000,1.00000,-1.00000] Explanation: Given: a / b = 2.0, b / c = 3.0 queries are: a / c = ?, b / a = ?, a / e = ?, a / a = ?, x / x = ? return: [6.0, 0.5, -1.0, 1.0, -1.0 ] note: x is undefined => -1.0 Example 2: Input: equations = [["a","b"],["b","c"],["bc","cd"]], values = [1.5,2.5,5.0], queries = [["a","c"],["c","b"],["bc","cd"],["cd","bc"]] Output: [3.75000,0.40000,5.00000,0.20000] Example 3: Input: equations = [["a","b"]], values = [0.5], queries = [["a","b"],["b","a"],["a","c"],["x","y"]] Output: [0.50000,2.00000,-1.00000,-1.00000] Constraints: 1 <= equations.length <= 20 equations[i].length == 2 1 <= Ai.length, Bi.length <= 5 values.length == equations.length 0.0 < values[i] <= 20.0 1 <= queries.length <= 20 queries[i].length == 2 1 <= Cj.length, Dj.length <= 5 Ai, Bi, Cj, Dj consist of lower case English letters and digits.
[Python3] dfs & union-find
489
evaluate-division
0.596
ye15
Medium
6,938
399
nth digit
class Solution: def findNthDigit(self, n: int) -> int: digit = base = 1 # starting from 1 digit while n > 9*base*digit: # upper limit of d digits n -= 9*base*digit digit += 1 base *= 10 q, r = divmod(n-1, digit) return int(str(base + q)[r])
https://leetcode.com/problems/nth-digit/discuss/828924/Python3-O(logN)-solution
25
Given an integer n, return the nth digit of the infinite integer sequence [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ...]. Example 1: Input: n = 3 Output: 3 Example 2: Input: n = 11 Output: 0 Explanation: The 11th digit of the sequence 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ... is a 0, which is part of the number 10. Constraints: 1 <= n <= 231 - 1
[Python3] O(logN) solution
2,100
nth-digit
0.341
ye15
Medium
6,971
400
binary watch
class Solution: def readBinaryWatch(self, n: int) -> List[str]: return [str(h)+':'+'0'*(m<10)+str(m) for h in range(12) for m in range(60) if (bin(m)+bin(h)).count('1') == n]
https://leetcode.com/problems/binary-watch/discuss/371775/Solution-in-Python-3-(beats-~98)-(one-line)
10
A binary watch has 4 LEDs on the top to represent the hours (0-11), and 6 LEDs on the bottom to represent the minutes (0-59). Each LED represents a zero or one, with the least significant bit on the right. For example, the below binary watch reads "4:51". Given an integer turnedOn which represents the number of LEDs that are currently on (ignoring the PM), return all possible times the watch could represent. You may return the answer in any order. The hour must not contain a leading zero. For example, "01:00" is not valid. It should be "1:00". The minute must consist of two digits and may contain a leading zero. For example, "10:2" is not valid. It should be "10:02". Example 1: Input: turnedOn = 1 Output: ["0:01","0:02","0:04","0:08","0:16","0:32","1:00","2:00","4:00","8:00"] Example 2: Input: turnedOn = 9 Output: [] Constraints: 0 <= turnedOn <= 10
Solution in Python 3 (beats ~98%) (one line)
1,600
binary-watch
0.517
junaidmansuri
Easy
6,979
401
remove k digits
class Solution: def removeKdigits(self, num: str, k: int) -> str: st = list() for n in num: while st and k and st[-1] > n: st.pop() k -= 1 if st or n is not '0': # prevent leading zeros st.append(n) if k: # not fully spent st = st[0:-k] return ''.join(st) or '0'
https://leetcode.com/problems/remove-k-digits/discuss/1779520/Python3-MONOTONIC-STACK-(oo)-Explained
121
Given string num representing a non-negative integer num, and an integer k, return the smallest possible integer after removing k digits from num. Example 1: Input: num = "1432219", k = 3 Output: "1219" Explanation: Remove the three digits 4, 3, and 2 to form the new number 1219 which is the smallest. Example 2: Input: num = "10200", k = 1 Output: "200" Explanation: Remove the leading 1 and the number is 200. Note that the output must not contain leading zeroes. Example 3: Input: num = "10", k = 2 Output: "0" Explanation: Remove all the digits from the number and it is left with nothing which is 0. Constraints: 1 <= k <= num.length <= 105 num consists of only digits. num does not have any leading zeros except for the zero itself.
✔️ [Python3] MONOTONIC STACK (o^^o)♪, Explained
7,900
remove-k-digits
0.305
artod
Medium
6,998
402
frog jump
class Solution(object): def canCross(self, stones): n = len(stones) stoneSet = set(stones) visited = set() def goFurther(value,units): if (value+units not in stoneSet) or ((value,units) in visited): return False if value+units == stones[n-1]: return True visited.add((value,units)) return goFurther(value+units,units) or goFurther(value+units,units-1) or goFurther(value+units,units+1) return goFurther(stones[0],1)
https://leetcode.com/problems/frog-jump/discuss/418003/11-line-DFS-solution
20
A frog is crossing a river. The river is divided into some number of units, and at each unit, there may or may not exist a stone. The frog can jump on a stone, but it must not jump into the water. Given a list of stones positions (in units) in sorted ascending order, determine if the frog can cross the river by landing on the last stone. Initially, the frog is on the first stone and assumes the first jump must be 1 unit. If the frog's last jump was k units, its next jump must be either k - 1, k, or k + 1 units. The frog can only jump in the forward direction. Example 1: Input: stones = [0,1,3,5,6,8,12,17] Output: true Explanation: The frog can jump to the last stone by jumping 1 unit to the 2nd stone, then 2 units to the 3rd stone, then 2 units to the 4th stone, then 3 units to the 6th stone, 4 units to the 7th stone, and 5 units to the 8th stone. Example 2: Input: stones = [0,1,2,3,4,8,9,11] Output: false Explanation: There is no way to jump to the last stone as the gap between the 5th and 6th stone is too large. Constraints: 2 <= stones.length <= 2000 0 <= stones[i] <= 231 - 1 stones[0] == 0 stones is sorted in a strictly increasing order.
11 line DFS solution
2,700
frog-jump
0.432
nirajmotiani
Hard
7,025
403
sum of left leaves
class Solution: def sumOfLeftLeaves(self, root: Optional[TreeNode]) -> int: if not root: return 0 # does this node have a left child which is a leaf? if root.left and not root.left.left and not root.left.right: # gotcha return root.left.val + self.sumOfLeftLeaves(root.right) # no it does not have a left child or it's not a leaf else: # bummer return self.sumOfLeftLeaves(root.left) + self.sumOfLeftLeaves(root.right)
https://leetcode.com/problems/sum-of-left-leaves/discuss/1558223/Python-DFSRecursion-Easy-%2B-Intuitive
36
Given the root of a binary tree, return the sum of all left leaves. A leaf is a node with no children. A left leaf is a leaf that is the left child of another node. Example 1: Input: root = [3,9,20,null,null,15,7] Output: 24 Explanation: There are two left leaves in the binary tree, with values 9 and 15 respectively. Example 2: Input: root = [1] Output: 0 Constraints: The number of nodes in the tree is in the range [1, 1000]. -1000 <= Node.val <= 1000
Python DFS/Recursion Easy + Intuitive
2,000
sum-of-left-leaves
0.563
aayushisingh1703
Easy
7,041
404
convert a number to hexadecimal
class Solution: def toHex(self, num: int) -> str: hex="0123456789abcdef" #created string for reference ot="" # created a string variable to store and update output string if num==0: return "0" elif num<0: num+=2**32 while num: ot=hex[num%16]+ot # we update the output string with the reminder of num/16 , 16 because we are dealing with hex. num//=16 # now we are updating num by dividing it by 16 ***// operator used for floor division , means division will be always integer not float. return ot # then we simply return ot
https://leetcode.com/problems/convert-a-number-to-hexadecimal/discuss/1235709/easy-solution-with-explanation
12
Given an integer num, return a string representing its hexadecimal representation. For negative integers, two’s complement method is used. All the letters in the answer string should be lowercase characters, and there should not be any leading zeros in the answer except for the zero itself. Note: You are not allowed to use any built-in library method to directly solve this problem. Example 1: Input: num = 26 Output: "1a" Example 2: Input: num = -1 Output: "ffffffff" Constraints: -231 <= num <= 231 - 1
easy solution with explanation
756
convert-a-number-to-hexadecimal
0.462
souravsingpardeshi
Easy
7,071
405
queue reconstruction by height
class Solution: def reconstructQueue(self, people: List[List[int]]) -> List[List[int]]: output=[] # sort the array in decreasing order of height # within the same height group, you would sort it in increasing order of k # eg: Input : [[7,0],[4,4],[7,1],[5,0],[6,1],[5,2]] # after sorting: [[7,0],[7,1],[6,1],[5,0],[5,2],[4,4]] people.sort(key=lambda x: (-x[0], x[1])) for a in people: # Now let's start the greedy here # We insert the entry in the output array based on the k value # k will act as a position within the array output.insert(a[1], a) return output
https://leetcode.com/problems/queue-reconstruction-by-height/discuss/2211602/Python-Easy-Greedy-O(1)-Space-approach
79
You are given an array of people, people, which are the attributes of some people in a queue (not necessarily in order). Each people[i] = [hi, ki] represents the ith person of height hi with exactly ki other people in front who have a height greater than or equal to hi. Reconstruct and return the queue that is represented by the input array people. The returned queue should be formatted as an array queue, where queue[j] = [hj, kj] is the attributes of the jth person in the queue (queue[0] is the person at the front of the queue). Example 1: Input: people = [[7,0],[4,4],[7,1],[5,0],[6,1],[5,2]] Output: [[5,0],[7,0],[5,2],[6,1],[4,4],[7,1]] Explanation: Person 0 has height 5 with no other people taller or the same height in front. Person 1 has height 7 with no other people taller or the same height in front. Person 2 has height 5 with two persons taller or the same height in front, which is person 0 and 1. Person 3 has height 6 with one person taller or the same height in front, which is person 1. Person 4 has height 4 with four people taller or the same height in front, which are people 0, 1, 2, and 3. Person 5 has height 7 with one person taller or the same height in front, which is person 1. Hence [[5,0],[7,0],[5,2],[6,1],[4,4],[7,1]] is the reconstructed queue. Example 2: Input: people = [[6,0],[5,0],[4,0],[3,2],[2,2],[1,4]] Output: [[4,0],[5,0],[2,2],[3,2],[1,4],[6,0]] Constraints: 1 <= people.length <= 2000 0 <= hi <= 106 0 <= ki < people.length It is guaranteed that the queue can be reconstructed.
Python Easy Greedy O(1) Space approach
3,300
queue-reconstruction-by-height
0.728
constantine786
Medium
7,092
406
trapping rain water ii
class Solution: def trapRainWater(self, heightMap: List[List[int]]) -> int: if not heightMap or not heightMap[0]: return 0 # Initial # Board cells cannot trap the water m, n = len(heightMap), len(heightMap[0]) if m < 3 or n < 3: return 0 # Add Board cells first heap = [] for i in range(m): for j in range(n): if i == 0 or i == m - 1 or j == 0 or j == n - 1: heapq.heappush(heap, (heightMap[i][j], i, j)) heightMap[i][j] = -1 # Start from level 0 level, res = 0, 0 while heap: height, x, y = heapq.heappop(heap) level = max(height, level) for i, j in [(x - 1, y), (x + 1, y), (x, y - 1), (x, y + 1)]: if 0 <= i < m and 0 <= j < n and heightMap[i][j] != -1: heapq.heappush(heap, (heightMap[i][j], i, j)) # If cell's height smaller than the level, then it can trap the rain water if heightMap[i][j] < level: res += level - heightMap[i][j] # Set the height to -1 if the cell is visited heightMap[i][j] = -1 return res
https://leetcode.com/problems/trapping-rain-water-ii/discuss/1138028/Python3Visualization-BFS-Solution-With-Explanation
209
Given an m x n integer matrix heightMap representing the height of each unit cell in a 2D elevation map, return the volume of water it can trap after raining. Example 1: Input: heightMap = [[1,4,3,1,3,2],[3,2,1,3,2,4],[2,3,3,2,3,1]] Output: 4 Explanation: After the rain, water is trapped between the blocks. We have two small ponds 1 and 3 units trapped. The total volume of water trapped is 4. Example 2: Input: heightMap = [[3,3,3,3,3],[3,2,2,2,3],[3,2,1,2,3],[3,2,2,2,3],[3,3,3,3,3]] Output: 10 Constraints: m == heightMap.length n == heightMap[i].length 1 <= m, n <= 200 0 <= heightMap[i][j] <= 2 * 104
[Python3][Visualization] BFS Solution With Explanation
4,700
trapping-rain-water-ii
0.475
Picassos_Shoes
Hard
7,114
407
longest palindrome
class Solution: def longestPalindrome(self, s: str) -> int: oddFlag=0 count=collections.Counter(s) ans=0 for k,v in count.items(): if v%2==1: ans+=v-1 oddFlag= 1 else: ans+=v if oddFlag == 1: return ans+1 return ans
https://leetcode.com/problems/longest-palindrome/discuss/2221045/Python-oror-counter-oror-explanation
9
Given a string s which consists of lowercase or uppercase letters, return the length of the longest palindrome that can be built with those letters. Letters are case sensitive, for example, "Aa" is not considered a palindrome here. Example 1: Input: s = "abccccdd" Output: 7 Explanation: One longest palindrome that can be built is "dccaccd", whose length is 7. Example 2: Input: s = "a" Output: 1 Explanation: The longest palindrome that can be built is "a", whose length is 1. Constraints: 1 <= s.length <= 2000 s consists of lowercase and/or uppercase English letters only.
Python || counter || explanation
465
longest-palindrome
0.547
palashbajpai214
Easy
7,120
409
split array largest sum
class Solution: def splitArray(self, nums: List[int], m: int) -> int: def isPossible(maxSum): curr = count = 0 for i in nums: count += (i + curr > maxSum) curr = curr + i if i + curr <= maxSum else i return count + 1 <= m lo, hi = max(nums), sum(nums) while lo <= hi: mid = (lo + hi) // 2 if isPossible(mid): hi = mid - 1 else: lo = mid + 1 return lo
https://leetcode.com/problems/split-array-largest-sum/discuss/1901138/Python-Short-and-Simple-NLogSum
3
Given an integer array nums and an integer k, split nums into k non-empty subarrays such that the largest sum of any subarray is minimized. Return the minimized largest sum of the split. A subarray is a contiguous part of the array. Example 1: Input: nums = [7,2,5,10,8], k = 2 Output: 18 Explanation: There are four ways to split nums into two subarrays. The best way is to split it into [7,2,5] and [10,8], where the largest sum among the two subarrays is only 18. Example 2: Input: nums = [1,2,3,4,5], k = 2 Output: 9 Explanation: There are four ways to split nums into two subarrays. The best way is to split it into [1,2,3] and [4,5], where the largest sum among the two subarrays is only 9. Constraints: 1 <= nums.length <= 1000 0 <= nums[i] <= 106 1 <= k <= min(50, nums.length)
✅ Python Short and Simple NLogSum
112
split-array-largest-sum
0.533
dhananjay79
Hard
7,161
410
fizz buzz
class Solution: def fizzBuzz(self, n: int) -> List[str]: return ['FizzBuzz' if i%15 == 0 else 'Buzz' if i%5 == 0 else 'Fizz' if i%3 == 0 else str(i) for i in range(1,n+1)] - Junaid Mansuri (LeetCode ID)@hotmail.com
https://leetcode.com/problems/fizz-buzz/discuss/380065/Solution-in-Python-3-(beats-~98)-(one-line)
6
Given an integer n, return a string array answer (1-indexed) where: answer[i] == "FizzBuzz" if i is divisible by 3 and 5. answer[i] == "Fizz" if i is divisible by 3. answer[i] == "Buzz" if i is divisible by 5. answer[i] == i (as a string) if none of the above conditions are true. Example 1: Input: n = 3 Output: ["1","2","Fizz"] Example 2: Input: n = 5 Output: ["1","2","Fizz","4","Buzz"] Example 3: Input: n = 15 Output: ["1","2","Fizz","4","Buzz","Fizz","7","8","Fizz","Buzz","11","Fizz","13","14","FizzBuzz"] Constraints: 1 <= n <= 104
Solution in Python 3 (beats ~98%) (one line)
1,900
fizz-buzz
0.69
junaidmansuri
Easy
7,186
412
arithmetic slices
class Solution: def numberOfArithmeticSlices(self, nums: List[int]) -> int: count = 0 for i in range(len(nums)-2): j = i+1 while(j<len(nums)-1): if nums[j]-nums[j-1] == nums[j+1]-nums[j]: count += 1 j += 1 else: break return count
https://leetcode.com/problems/arithmetic-slices/discuss/1816132/beginners-solution-Easy-to-understand
3
An integer array is called arithmetic if it consists of at least three elements and if the difference between any two consecutive elements is the same. For example, [1,3,5,7,9], [7,7,7,7], and [3,-1,-5,-9] are arithmetic sequences. Given an integer array nums, return the number of arithmetic subarrays of nums. A subarray is a contiguous subsequence of the array. Example 1: Input: nums = [1,2,3,4] Output: 3 Explanation: We have 3 arithmetic slices in nums: [1, 2, 3], [2, 3, 4] and [1,2,3,4] itself. Example 2: Input: nums = [1] Output: 0 Constraints: 1 <= nums.length <= 5000 -1000 <= nums[i] <= 1000
beginners solution, Easy to understand
201
arithmetic-slices
0.651
harshsatpute16201
Medium
7,239
413
third maximum number
class Solution: def thirdMax(self, nums: List[int]) -> int: n, T = list(set(nums)), [float('-inf')]*3 for i in n: if i > T[0]: T = [i,T[0],T[1]] continue if i > T[1]: T = [T[0],i,T[1]] continue if i > T[2]: T = [T[0],T[1],i] return T[2] if T[2] != float('-inf') else T[0] - Junaid Mansuri
https://leetcode.com/problems/third-maximum-number/discuss/352011/Solution-in-Python-3-(beats-~99)-(-O(n)-)
18
Given an integer array nums, return the third distinct maximum number in this array. If the third maximum does not exist, return the maximum number. Example 1: Input: nums = [3,2,1] Output: 1 Explanation: The first distinct maximum is 3. The second distinct maximum is 2. The third distinct maximum is 1. Example 2: Input: nums = [1,2] Output: 2 Explanation: The first distinct maximum is 2. The second distinct maximum is 1. The third distinct maximum does not exist, so the maximum (2) is returned instead. Example 3: Input: nums = [2,2,3,1] Output: 1 Explanation: The first distinct maximum is 3. The second distinct maximum is 2 (both 2's are counted together since they have the same value). The third distinct maximum is 1. Constraints: 1 <= nums.length <= 104 -231 <= nums[i] <= 231 - 1 Follow up: Can you find an O(n) solution?
Solution in Python 3 (beats ~99%) ( O(n) )
3,500
third-maximum-number
0.326
junaidmansuri
Easy
7,282
414
add strings
class Solution: def addStrings(self, num1: str, num2: str) -> str: num1 = list(num1) num2 = list(num2) car = 0 res = "" while num1 or num2 or car: if num1: car += int(num1.pop()) if num2: car += int(num2.pop()) res += str((car % 10)) car //= 10 return res[::-1]
https://leetcode.com/problems/add-strings/discuss/1591891/Python-Straightforward-Solution-or-Easy-to-Understand
10
Given two non-negative integers, num1 and num2 represented as string, return the sum of num1 and num2 as a string. You must solve the problem without using any built-in library for handling large integers (such as BigInteger). You must also not convert the inputs to integers directly. Example 1: Input: num1 = "11", num2 = "123" Output: "134" Example 2: Input: num1 = "456", num2 = "77" Output: "533" Example 3: Input: num1 = "0", num2 = "0" Output: "0" Constraints: 1 <= num1.length, num2.length <= 104 num1 and num2 consist of only digits. num1 and num2 don't have any leading zeros except for the zero itself.
Python Straightforward Solution | Easy to Understand
605
add-strings
0.526
leet_satyam
Easy
7,334
415
partition equal subset sum
class Solution: def canPartition(self, nums: List[int]) -> bool: if sum(nums)%2: # or if sum(nums)&amp;1 return False # main logic here
https://leetcode.com/problems/partition-equal-subset-sum/discuss/1624391/Python-DP-and-DFS-Solutions-Easy-to-understand-with-Explanation
38
Given an integer array nums, return true if you can partition the array into two subsets such that the sum of the elements in both subsets is equal or false otherwise. Example 1: Input: nums = [1,5,11,5] Output: true Explanation: The array can be partitioned as [1, 5, 5] and [11]. Example 2: Input: nums = [1,2,3,5] Output: false Explanation: The array cannot be partitioned into equal sum subsets. Constraints: 1 <= nums.length <= 200 1 <= nums[i] <= 100
[Python] DP & DFS Solutions - Easy-to-understand with Explanation
5,800
partition-equal-subset-sum
0.466
zayne-siew
Medium
7,384
416
pacific atlantic water flow
class Solution: def pacificAtlantic(self, ht: List[List[int]]) -> List[List[int]]: def pac(i,j): if rp[i][j]: return True k=False h=ht[i][j] ht[i][j]=100001 if ht[i-1][j]<=h: k=k or pac(i-1,j) if ht[i][j-1]<=h: k=k or pac(i,j-1) if i<m-1 and ht[i+1][j]<=h: k=k or pac(i+1,j) if j<n-1 and ht[i][j+1]<=h: k=k or pac(i,j+1) ht[i][j]=h rp[i][j]=k return k def ant(i,j): if ra[i][j]: return True k=False h=ht[i][j] ht[i][j]=100001 if i>0 and ht[i-1][j]<=h: k=k or ant(i-1,j) if j>0 and ht[i][j-1]<=h: k=k or ant(i,j-1) if ht[i+1][j]<=h: k=k or ant(i+1,j) if ht[i][j+1]<=h: k=k or ant(i,j+1) ht[i][j]=h ra[i][j]=k return k m=len(ht) n=len(ht[0]) rp=[[False for i in range(n)] for j in range(m)] ra=[[False for i in range(n)] for j in range(m)] for i in range(m): rp[i][0]=True ra[i][-1]=True for i in range(n): rp[0][i]=True ra[-1][i]=True for i in range(m): for j in range(n): pac(i,j) ant(i,j) res=[] for i in range(m): for j in range(n): if rp[i][j] and ra[i][j]: res.append([i,j]) return res
https://leetcode.com/problems/pacific-atlantic-water-flow/discuss/2507252/PYTHON-oror-EXPLAINED-oror
16
There is an m x n rectangular island that borders both the Pacific Ocean and Atlantic Ocean. The Pacific Ocean touches the island's left and top edges, and the Atlantic Ocean touches the island's right and bottom edges. The island is partitioned into a grid of square cells. You are given an m x n integer matrix heights where heights[r][c] represents the height above sea level of the cell at coordinate (r, c). The island receives a lot of rain, and the rain water can flow to neighboring cells directly north, south, east, and west if the neighboring cell's height is less than or equal to the current cell's height. Water can flow from any cell adjacent to an ocean into the ocean. Return a 2D list of grid coordinates result where result[i] = [ri, ci] denotes that rain water can flow from cell (ri, ci) to both the Pacific and Atlantic oceans. Example 1: Input: heights = [[1,2,2,3,5],[3,2,3,4,4],[2,4,5,3,1],[6,7,1,4,5],[5,1,1,2,4]] Output: [[0,4],[1,3],[1,4],[2,2],[3,0],[3,1],[4,0]] Explanation: The following cells can flow to the Pacific and Atlantic oceans, as shown below: [0,4]: [0,4] -> Pacific Ocean [0,4] -> Atlantic Ocean [1,3]: [1,3] -> [0,3] -> Pacific Ocean [1,3] -> [1,4] -> Atlantic Ocean [1,4]: [1,4] -> [1,3] -> [0,3] -> Pacific Ocean [1,4] -> Atlantic Ocean [2,2]: [2,2] -> [1,2] -> [0,2] -> Pacific Ocean [2,2] -> [2,3] -> [2,4] -> Atlantic Ocean [3,0]: [3,0] -> Pacific Ocean [3,0] -> [4,0] -> Atlantic Ocean [3,1]: [3,1] -> [3,0] -> Pacific Ocean [3,1] -> [4,1] -> Atlantic Ocean [4,0]: [4,0] -> Pacific Ocean [4,0] -> Atlantic Ocean Note that there are other possible paths for these cells to flow to the Pacific and Atlantic oceans. Example 2: Input: heights = [[1]] Output: [[0,0]] Explanation: The water can flow from the only cell to the Pacific and Atlantic oceans. Constraints: m == heights.length n == heights[r].length 1 <= m, n <= 200 0 <= heights[r][c] <= 105
🥇 PYTHON || EXPLAINED || ; ]
1,900
pacific-atlantic-water-flow
0.541
karan_8082
Medium
7,432
417
battleships in a board
class Solution: def countBattleships(self, board: List[List[str]]) -> int: count = 0 for r in range(len(board)): for c in range(len(board[0])): if board[r][c] == 'X': var = 1 if (r > 0 and board[r-1][c] == 'X') or (c > 0 and board[r][c-1] == 'X'): var = 0 count += var return count
https://leetcode.com/problems/battleships-in-a-board/discuss/1523048/Simple-Easy-to-Understand-Python-O(1)-extra-memory
9
Given an m x n matrix board where each cell is a battleship 'X' or empty '.', return the number of the battleships on board. Battleships can only be placed horizontally or vertically on board. In other words, they can only be made of the shape 1 x k (1 row, k columns) or k x 1 (k rows, 1 column), where k can be of any size. At least one horizontal or vertical cell separates between two battleships (i.e., there are no adjacent battleships). Example 1: Input: board = [["X",".",".","X"],[".",".",".","X"],[".",".",".","X"]] Output: 2 Example 2: Input: board = [["."]] Output: 0 Constraints: m == board.length n == board[i].length 1 <= m, n <= 200 board[i][j] is either '.' or 'X'. Follow up: Could you do it in one-pass, using only O(1) extra memory and without modifying the values board?
Simple Easy to Understand Python O(1) extra memory
638
battleships-in-a-board
0.747
bshien
Medium
7,472
419
strong password checker
class Solution: def strongPasswordChecker(self, password: str) -> int: #vimla_kushwaha s = password missing_type = 3 if any('a' <= c <= 'z' for c in s): missing_type -= 1 if any('A' <= c <= 'Z' for c in s): missing_type -= 1 if any(c.isdigit() for c in s): missing_type -= 1 change = 0 one = two = 0 p = 2 while p < len(s): if s[p] == s[p-1] == s[p-2]: length = 2 while p < len(s) and s[p] == s[p-1]: length += 1 p += 1 change += length // 3 if length % 3 == 0: one += 1 elif length % 3 == 1: two += 1 else: p += 1 if len(s) < 6: return max(missing_type, 6 - len(s)) elif len(s) <= 20: return max(missing_type, change) else: delete = len(s) - 20 change -= min(delete, one) change -= min(max(delete - one, 0), two * 2) // 2 change -= max(delete - one - 2 * two, 0) // 3 return int(delete + max(missing_type, change))
https://leetcode.com/problems/strong-password-checker/discuss/2345991/Runtime%3A-23-ms-or-Memory-Usage%3A-13.9-MB-or-python3
2
A password is considered strong if the below conditions are all met: It has at least 6 characters and at most 20 characters. It contains at least one lowercase letter, at least one uppercase letter, and at least one digit. It does not contain three repeating characters in a row (i.e., "Baaabb0" is weak, but "Baaba0" is strong). Given a string password, return the minimum number of steps required to make password strong. if password is already strong, return 0. In one step, you can: Insert one character to password, Delete one character from password, or Replace one character of password with another character. Example 1: Input: password = "a" Output: 5 Example 2: Input: password = "aA1" Output: 3 Example 3: Input: password = "1337C0d3" Output: 0 Constraints: 1 <= password.length <= 50 password consists of letters, digits, dot '.' or exclamation mark '!'.
Runtime: 23 ms | Memory Usage: 13.9 MB | python3
309
strong-password-checker
0.143
vimla_kushwaha
Hard
7,489
420
maximum xor of two numbers in an array
class Solution: def findMaximumXOR(self, nums: List[int]) -> int: # need to know the largest binary representation # bin prepends '0b', ignore L = len(bin(max(nums))) - 2 # preprocess step - left-pad zeros to ensure each number has L bits # (x >> i) &amp; 1 produces the bit at position i for number x # x's value is moved right by i bits, we &amp; 1 to produce 0 or 1 # e.g., if L = 5, then 3 = [0, 0, 0, 1, 1], so the steps to get there are: # (3 >> 4) &amp; 1 = 0 # (3 >> 3) &amp; 1 = 0 # (3 >> 2) &amp; 1 = 0 # (3 >> 1) &amp; 1 = 1 # (3 >> 0) &amp; 1 = 1 nums_bits = [[(x >> i) &amp; 1 for i in reversed(range(L))] for x in nums] root = {} # build the trie for num, bits in zip(nums, nums_bits): node = root for bit in bits: node = node.setdefault(bit, {}) node["#"] = num max_xor = 0 for num, bits in zip(nums, nums_bits): node = root # we want to find the node that will produce the largest XOR with num for bit in bits: # our goal is to find the opposite bit, e.g. bit = 0, we want 1 # this is our goal because we want as many 1's as possible toggled_bit = 1 - bit if toggled_bit in node: node = node[toggled_bit] else: node = node[bit] # we're at a leaf node, now we can do the XOR computation max_xor = max(max_xor, node["#"] ^ num) return max_xor
https://leetcode.com/problems/maximum-xor-of-two-numbers-in-an-array/discuss/404504/Python-O(N)-Trie-Solution-wcomments-and-explanations
2
Given an integer array nums, return the maximum result of nums[i] XOR nums[j], where 0 <= i <= j < n. Example 1: Input: nums = [3,10,5,25,2,8] Output: 28 Explanation: The maximum result is 5 XOR 25 = 28. Example 2: Input: nums = [14,70,53,83,49,91,36,80,92,51,66,70] Output: 127 Constraints: 1 <= nums.length <= 2 * 105 0 <= nums[i] <= 231 - 1
Python O(N) Trie Solution w/comments and explanations
904
maximum-xor-of-two-numbers-in-an-array
0.545
crippled_baby
Medium
7,492
421
reconstruct original digits from english
class Solution: def originalDigits(self, s: str) -> str: c = collections.Counter(s) digit_count = [0] * 10 digit_count[0] = c['z'] digit_count[2] = c['w'] digit_count[4] = c['u'] digit_count[6] = c['x'] digit_count[8] = c['g'] digit_count[3] = c['h'] - digit_count[8] digit_count[5] = c['f'] - digit_count[4] digit_count[7] = c['s'] - digit_count[6] digit_count[9] = c['i'] - digit_count[5] - digit_count[6] - digit_count[8] digit_count[1] = c['n'] - digit_count[9] * 2 - digit_count[7] return "".join([str(idx) * cnt for idx, cnt in enumerate(digit_count) if cnt > 0])
https://leetcode.com/problems/reconstruct-original-digits-from-english/discuss/1556493/Python3-One-pass-solution
2
Given a string s containing an out-of-order English representation of digits 0-9, return the digits in ascending order. Example 1: Input: s = "owoztneoer" Output: "012" Example 2: Input: s = "fviefuro" Output: "45" Constraints: 1 <= s.length <= 105 s[i] is one of the characters ["e","g","f","i","h","o","n","s","r","u","t","w","v","x","z"]. s is guaranteed to be valid.
[Python3] One pass solution
361
reconstruct-original-digits-from-english
0.513
maosipov11
Medium
7,499
423
longest repeating character replacement
class Solution: def characterReplacement(self, s: str, k: int) -> int: # Maintain a dictionary that keeps track of last 'window' characters # See if 'window' size minus occurrences of the most common char is <= k, if so it's valid # Run time is O(length of string * size of alphabet) # Space is O(size of alphabet) d = {} window = 0 for i, char in enumerate(s): d[char] = d.get(char, 0) + 1 if window+1 - max(d.values()) <= k: window += 1 else: d[s[i-window]] -= 1 return window
https://leetcode.com/problems/longest-repeating-character-replacement/discuss/900524/Simple-Python-solution-moving-window-O(n)-time-O(1)-space
16
You are given a string s and an integer k. You can choose any character of the string and change it to any other uppercase English character. You can perform this operation at most k times. Return the length of the longest substring containing the same letter you can get after performing the above operations. Example 1: Input: s = "ABAB", k = 2 Output: 4 Explanation: Replace the two 'A's with two 'B's or vice versa. Example 2: Input: s = "AABABBA", k = 1 Output: 4 Explanation: Replace the one 'A' in the middle with 'B' and form "AABBBBA". The substring "BBBB" has the longest repeating letters, which is 4. There may exists other ways to achieve this answer too. Constraints: 1 <= s.length <= 105 s consists of only uppercase English letters. 0 <= k <= s.length
Simple Python solution, moving window O(n) time, O(1) space
2,100
longest-repeating-character-replacement
0.515
wesleyliao3
Medium
7,505
424
construct quad tree
class Solution: def construct(self, grid: List[List[int]]) -> 'Node': def fn(x0, x1, y0, y1): """Return QuadTree subtree.""" val = {grid[i][j] for i, j in product(range(x0, x1), range(y0, y1))} if len(val) == 1: return Node(val.pop(), True, None, None, None, None) tl = fn(x0, (x0+x1)//2, y0, (y0+y1)//2) tr = fn(x0, (x0+x1)//2, (y0+y1)//2, y1) bl = fn((x0+x1)//2, x1, y0, (y0+y1)//2) br = fn((x0+x1)//2, x1, (y0+y1)//2, y1) return Node(None, False, tl, tr, bl, br) n = len(grid) return fn(0, n, 0, n)
https://leetcode.com/problems/construct-quad-tree/discuss/874250/Python3-building-tree-recursively
2
Given a n * n matrix grid of 0's and 1's only. We want to represent grid with a Quad-Tree. Return the root of the Quad-Tree representing grid. A Quad-Tree is a tree data structure in which each internal node has exactly four children. Besides, each node has two attributes: val: True if the node represents a grid of 1's or False if the node represents a grid of 0's. Notice that you can assign the val to True or False when isLeaf is False, and both are accepted in the answer. isLeaf: True if the node is a leaf node on the tree or False if the node has four children. class Node { public boolean val; public boolean isLeaf; public Node topLeft; public Node topRight; public Node bottomLeft; public Node bottomRight; } We can construct a Quad-Tree from a two-dimensional area using the following steps: If the current grid has the same value (i.e all 1's or all 0's) set isLeaf True and set val to the value of the grid and set the four children to Null and stop. If the current grid has different values, set isLeaf to False and set val to any value and divide the current grid into four sub-grids as shown in the photo. Recurse for each of the children with the proper sub-grid. If you want to know more about the Quad-Tree, you can refer to the wiki. Quad-Tree format: You don't need to read this section for solving the problem. This is only if you want to understand the output format here. The output represents the serialized format of a Quad-Tree using level order traversal, where null signifies a path terminator where no node exists below. It is very similar to the serialization of the binary tree. The only difference is that the node is represented as a list [isLeaf, val]. If the value of isLeaf or val is True we represent it as 1 in the list [isLeaf, val] and if the value of isLeaf or val is False we represent it as 0. Example 1: Input: grid = [[0,1],[1,0]] Output: [[0,1],[1,0],[1,1],[1,1],[1,0]] Explanation: The explanation of this example is shown below: Notice that 0 represents False and 1 represents True in the photo representing the Quad-Tree. Example 2: Input: grid = [[1,1,1,1,0,0,0,0],[1,1,1,1,0,0,0,0],[1,1,1,1,1,1,1,1],[1,1,1,1,1,1,1,1],[1,1,1,1,0,0,0,0],[1,1,1,1,0,0,0,0],[1,1,1,1,0,0,0,0],[1,1,1,1,0,0,0,0]] Output: [[0,1],[1,1],[0,1],[1,1],[1,0],null,null,null,null,[1,0],[1,0],[1,1],[1,1]] Explanation: All values in the grid are not the same. We divide the grid into four sub-grids. The topLeft, bottomLeft and bottomRight each has the same value. The topRight have different values so we divide it into 4 sub-grids where each has the same value. Explanation is shown in the photo below: Constraints: n == grid.length == grid[i].length n == 2x where 0 <= x <= 6
[Python3] building tree recursively
167
construct-quad-tree
0.663
ye15
Medium
7,552
427
n ary tree level order traversal
class Solution: def levelOrder(self, root: 'Node') -> List[List[int]]: result = [] q = deque([root] if root else []) while q: result.append([]) for _ in range(len(q)): node = q.popleft() result[-1].append(node.val) q.extend(node.children) return result
https://leetcode.com/problems/n-ary-tree-level-order-traversal/discuss/2532005/Python-BFS
14
Given an n-ary tree, return the level order traversal of its nodes' values. Nary-Tree input serialization is represented in their level order traversal, each group of children is separated by the null value (See examples). Example 1: Input: root = [1,null,3,2,4,null,5,6] Output: [[1],[3,2,4],[5,6]] Example 2: Input: root = [1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14] Output: [[1],[2,3,4,5],[6,7,8,9,10],[11,12,13],[14]] Constraints: The height of the n-ary tree is less than or equal to 1000 The total number of nodes is between [0, 104]
Python, BFS
1,300
n-ary-tree-level-order-traversal
0.706
blue_sky5
Medium
7,558
429
flatten a multilevel doubly linked list
class Solution: def flatten(self, head: 'Node') -> 'Node': def getTail(node): prev = None while node: _next = node.next if node.child: # ... <-> node <-> node.child <-> ... node.next = node.child node.child = None node.next.prev = node # get the end node of the node.child list prev = getTail(node.next) if _next: # ... <-> prev (end node) <-> _next (originally node.next) <-> ... _next.prev = prev prev.next = _next else: prev = node node = _next # loop through the list of nodes return prev # return end node getTail(head) return head
https://leetcode.com/problems/flatten-a-multilevel-doubly-linked-list/discuss/1550377/Python-Recursion%3A-Easy-to-understand-with-Explanation
6
You are given a doubly linked list, which contains nodes that have a next pointer, a previous pointer, and an additional child pointer. This child pointer may or may not point to a separate doubly linked list, also containing these special nodes. These child lists may have one or more children of their own, and so on, to produce a multilevel data structure as shown in the example below. Given the head of the first level of the list, flatten the list so that all the nodes appear in a single-level, doubly linked list. Let curr be a node with a child list. The nodes in the child list should appear after curr and before curr.next in the flattened list. Return the head of the flattened list. The nodes in the list must have all of their child pointers set to null. Example 1: Input: head = [1,2,3,4,5,6,null,null,null,7,8,9,10,null,null,11,12] Output: [1,2,3,7,8,11,12,9,10,4,5,6] Explanation: The multilevel linked list in the input is shown. After flattening the multilevel linked list it becomes: Example 2: Input: head = [1,2,null,3] Output: [1,3,2] Explanation: The multilevel linked list in the input is shown. After flattening the multilevel linked list it becomes: Example 3: Input: head = [] Output: [] Explanation: There could be empty list in the input. Constraints: The number of Nodes will not exceed 1000. 1 <= Node.val <= 105 How the multilevel linked list is represented in test cases: We use the multilevel linked list from Example 1 above: 1---2---3---4---5---6--NULL | 7---8---9---10--NULL | 11--12--NULL The serialization of each level is as follows: [1,2,3,4,5,6,null] [7,8,9,10,null] [11,12,null] To serialize all levels together, we will add nulls in each level to signify no node connects to the upper node of the previous level. The serialization becomes: [1, 2, 3, 4, 5, 6, null] | [null, null, 7, 8, 9, 10, null] | [ null, 11, 12, null] Merging the serialization of each level and removing trailing nulls we obtain: [1,2,3,4,5,6,null,null,null,7,8,9,10,null,null,11,12]
Python Recursion: Easy-to-understand with Explanation
501
flatten-a-multilevel-doubly-linked-list
0.595
zayne-siew
Medium
7,597
430
minimum genetic mutation
class Solution: def minMutation(self, start: str, end: str, bank: List[str]) -> int: dic=defaultdict(lambda :0) lst=[[start,0]] dic[start]=1 while lst: x,d=lst.pop(0) if x==end: return d for i in range(len(bank)): ct=0 for j in range(8): if x[j]!=bank[i][j]: ct+=1 if ct==1: if dic[bank[i]]==0: lst.append([bank[i],d+1]) dic[bank[i]]=1 return -1
https://leetcode.com/problems/minimum-genetic-mutation/discuss/2769493/SIMPLE-PYTHON-SOLUTION-USING-BFS
2
A gene string can be represented by an 8-character long string, with choices from 'A', 'C', 'G', and 'T'. Suppose we need to investigate a mutation from a gene string startGene to a gene string endGene where one mutation is defined as one single character changed in the gene string. For example, "AACCGGTT" --> "AACCGGTA" is one mutation. There is also a gene bank bank that records all the valid gene mutations. A gene must be in bank to make it a valid gene string. Given the two gene strings startGene and endGene and the gene bank bank, return the minimum number of mutations needed to mutate from startGene to endGene. If there is no such a mutation, return -1. Note that the starting point is assumed to be valid, so it might not be included in the bank. Example 1: Input: startGene = "AACCGGTT", endGene = "AACCGGTA", bank = ["AACCGGTA"] Output: 1 Example 2: Input: startGene = "AACCGGTT", endGene = "AAACGGTA", bank = ["AACCGGTA","AACCGCTA","AAACGGTA"] Output: 2 Constraints: 0 <= bank.length <= 10 startGene.length == endGene.length == bank[i].length == 8 startGene, endGene, and bank[i] consist of only the characters ['A', 'C', 'G', 'T'].
SIMPLE PYTHON SOLUTION USING BFS
148
minimum-genetic-mutation
0.52
beneath_ocean
Medium
7,622
433
number of segments in a string
class Solution: def countSegments(self, s: str) -> int: return len([i for i in s.split(" ") if i!=""])
https://leetcode.com/problems/number-of-segments-in-a-string/discuss/1015806/One-Line-python-Solution
3
Given a string s, return the number of segments in the string. A segment is defined to be a contiguous sequence of non-space characters. Example 1: Input: s = "Hello, my name is John" Output: 5 Explanation: The five segments are ["Hello,", "my", "name", "is", "John"] Example 2: Input: s = "Hello" Output: 1 Constraints: 0 <= s.length <= 300 s consists of lowercase and uppercase English letters, digits, or one of the following characters "!@#$%^&*()_+-=',.:". The only space character in s is ' '.
One Line python Solution
464
number-of-segments-in-a-string
0.377
moazmar
Easy
7,656
434
non overlapping intervals
class Solution: def eraseOverlapIntervals(self, intervals: List[List[int]]) -> int: intervals.sort(key=lambda x: x[1]) n = len(intervals) ans, curr = 1, intervals[0] for i in range(n): if intervals[i][0] >= curr[1]: ans += 1 curr = intervals[i] return n - ans
https://leetcode.com/problems/non-overlapping-intervals/discuss/1896849/Python-easy-to-read-and-understand-or-sorting
2
Given an array of intervals intervals where intervals[i] = [starti, endi], return the minimum number of intervals you need to remove to make the rest of the intervals non-overlapping. Example 1: Input: intervals = [[1,2],[2,3],[3,4],[1,3]] Output: 1 Explanation: [1,3] can be removed and the rest of the intervals are non-overlapping. Example 2: Input: intervals = [[1,2],[1,2],[1,2]] Output: 2 Explanation: You need to remove two [1,2] to make the rest of the intervals non-overlapping. Example 3: Input: intervals = [[1,2],[2,3]] Output: 0 Explanation: You don't need to remove any of the intervals since they're already non-overlapping. Constraints: 1 <= intervals.length <= 105 intervals[i].length == 2 -5 * 104 <= starti < endi <= 5 * 104
Python easy to read and understand | sorting
196
non-overlapping-intervals
0.499
sanial2001
Medium
7,682
435
find right interval
class Solution: def findRightInterval(self, intervals: List[List[int]]) -> List[int]: start = sorted([[intervals[i][0], i] for i in range(len(intervals))]) end = sorted([[intervals[i][1], i] for i in range(len(intervals))]) i = 0 res = [] for endVal, endIdx in end: while i < len(start) and (endVal > start[i][0]): i += 1 if i < len(start): res.append(start[i][1]) else: while len(res) < len(start): res.append(-1) ans = [] for i in range(len(end)): ans.append((end[i][1], res[i])) ans.sort() return [ele[1] for ele in sorted([[a[1], b] for a, b in zip(end, res)])]
https://leetcode.com/problems/find-right-interval/discuss/2812012/Python-Sort-and-Two-Pointers-(Same-approach-as-826.-Most-Profit-Assigning-Work)
0
You are given an array of intervals, where intervals[i] = [starti, endi] and each starti is unique. The right interval for an interval i is an interval j such that startj >= endi and startj is minimized. Note that i may equal j. Return an array of right interval indices for each interval i. If no right interval exists for interval i, then put -1 at index i. Example 1: Input: intervals = [[1,2]] Output: [-1] Explanation: There is only one interval in the collection, so it outputs -1. Example 2: Input: intervals = [[3,4],[2,3],[1,2]] Output: [-1,0,1] Explanation: There is no right interval for [3,4]. The right interval for [2,3] is [3,4] since start0 = 3 is the smallest start that is >= end1 = 3. The right interval for [1,2] is [2,3] since start1 = 2 is the smallest start that is >= end2 = 2. Example 3: Input: intervals = [[1,4],[2,3],[3,4]] Output: [-1,2,-1] Explanation: There is no right interval for [1,4] and [3,4]. The right interval for [2,3] is [3,4] since start2 = 3 is the smallest start that is >= end1 = 3. Constraints: 1 <= intervals.length <= 2 * 104 intervals[i].length == 2 -106 <= starti <= endi <= 106 The start point of each interval is unique.
[Python] Sort and Two Pointers (Same approach as # 826. Most Profit Assigning Work)
4
find-right-interval
0.504
low_key_low_key
Medium
7,700
436
path sum iii
class Solution: def pathSum(self, root: TreeNode, sum: int) -> int: global result result = 0 def dfs(node, target): if node is None: return find_path_from_node(node, target) dfs(node.left, target) dfs(node.right, target) def find_path_from_node(node, target): global result if node is None: return if node.val == target: result += 1 find_path_from_node(node.left, target-node.val) find_path_from_node(node.right, target-node.val) dfs(root, sum) return result
https://leetcode.com/problems/path-sum-iii/discuss/1049652/Python-Solution
14
Given the root of a binary tree and an integer targetSum, return the number of paths where the sum of the values along the path equals targetSum. The path does not need to start or end at the root or a leaf, but it must go downwards (i.e., traveling only from parent nodes to child nodes). Example 1: Input: root = [10,5,-3,3,2,null,11,3,-2,null,1], targetSum = 8 Output: 3 Explanation: The paths that sum to 8 are shown. Example 2: Input: root = [5,4,8,11,null,13,4,7,2,null,null,5,1], targetSum = 22 Output: 3 Constraints: The number of nodes in the tree is in the range [0, 1000]. -109 <= Node.val <= 109 -1000 <= targetSum <= 1000
Python Solution
631
path-sum-iii
0.486
dev-josh
Medium
7,713
437
find all anagrams in a string
class Solution: def findAnagrams(self, s: str, p: str) -> List[int]: # take counter of first n elements in s_dict with n = len(p) - 1 s_dict = collections.Counter(s[:len(p)-1]) # counter of p, this should not be changed p_dict = collections.Counter(p) start = 0 # final result list res = [] # We iterate over the string s, and in each step we check if s_dict and p_dict match for i in range(len(p)-1, len(s)): # updating the counter &amp; adding the character s_dict[s[i]] += 1 # checking if counters match if s_dict == p_dict: res.append(start) # remove the first element from counter s_dict[s[start]] -= 1 #if element count = 0, pop it from the counter if s_dict[s[start]] == 0: del s_dict[s[start]] start += 1 return res
https://leetcode.com/problems/find-all-anagrams-in-a-string/discuss/1738367/Python-Sliding-Window(-)-algorithm-Detailed-Explanation-Concise-Soln-or-Faster-than-80
16
Given two strings s and p, return an array of all the start indices of p's anagrams in s. You may return the answer in any order. An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once. Example 1: Input: s = "cbaebabacd", p = "abc" Output: [0,6] Explanation: The substring with start index = 0 is "cba", which is an anagram of "abc". The substring with start index = 6 is "bac", which is an anagram of "abc". Example 2: Input: s = "abab", p = "ab" Output: [0,1,2] Explanation: The substring with start index = 0 is "ab", which is an anagram of "ab". The substring with start index = 1 is "ba", which is an anagram of "ab". The substring with start index = 2 is "ab", which is an anagram of "ab". Constraints: 1 <= s.length, p.length <= 3 * 104 s and p consist of lowercase English letters.
🔎 Python - Sliding Window( 🚅 🪟) algorithm Detailed Explanation, Concise Soln | Faster than 80%
1,400
find-all-anagrams-in-a-string
0.49
mystic_sd2001
Medium
7,723
438
k th smallest in lexicographical order
class Solution: def findKthNumber(self, n: int, k: int) -> int: def fn(x): """Return node counts in denary trie.""" ans, diff = 0, 1 while x <= n: ans += min(n - x + 1, diff) x *= 10 diff *= 10 return ans x = 1 while k > 1: cnt = fn(x) if k > cnt: k -= cnt; x += 1 else: k -= 1; x *= 10 return x
https://leetcode.com/problems/k-th-smallest-in-lexicographical-order/discuss/1608540/Python3-traverse-denary-trie
3
Given two integers n and k, return the kth lexicographically smallest integer in the range [1, n]. Example 1: Input: n = 13, k = 2 Output: 10 Explanation: The lexicographical order is [1, 10, 11, 12, 13, 2, 3, 4, 5, 6, 7, 8, 9], so the second smallest number is 10. Example 2: Input: n = 1, k = 1 Output: 1 Constraints: 1 <= k <= n <= 109
[Python3] traverse denary trie
435
k-th-smallest-in-lexicographical-order
0.308
ye15
Hard
7,769
440
arranging coins
class Solution: def arrangeCoins(self, n: int) -> int: first = 1 last = n if n==1: return 1 while first <= last: mid = (first+last)//2 if mid*(mid+1) == 2*n: return mid elif mid*(mid+1) > 2*n: last = mid-1 else: first = mid+1 return last
https://leetcode.com/problems/arranging-coins/discuss/2801813/Python-Simple-Binary-Search
2
You have n coins and you want to build a staircase with these coins. The staircase consists of k rows where the ith row has exactly i coins. The last row of the staircase may be incomplete. Given the integer n, return the number of complete rows of the staircase you will build. Example 1: Input: n = 5 Output: 2 Explanation: Because the 3rd row is incomplete, we return 2. Example 2: Input: n = 8 Output: 3 Explanation: Because the 4th row is incomplete, we return 3. Constraints: 1 <= n <= 231 - 1
Python Simple Binary Search
69
arranging-coins
0.462
BhavyaBusireddy
Easy
7,770
441
find all duplicates in an array
class Solution: def findDuplicates(self, N: List[int]) -> List[int]: S, A = set(), [] for n in N: if n in S: A.append(n) else: S.add(n) return A
https://leetcode.com/problems/find-all-duplicates-in-an-array/discuss/396890/Two-Solutions-in-Python-3-(-O(n)-time-)-(-O(1)-space-)
9
Given an integer array nums of length n where all the integers of nums are in the range [1, n] and each integer appears once or twice, return an array of all the integers that appears twice. You must write an algorithm that runs in O(n) time and uses only constant extra space. Example 1: Input: nums = [4,3,2,7,8,2,3,1] Output: [2,3] Example 2: Input: nums = [1,1,2] Output: [1] Example 3: Input: nums = [1] Output: [] Constraints: n == nums.length 1 <= n <= 105 1 <= nums[i] <= n Each element in nums appears once or twice.
Two Solutions in Python 3 ( O(n) time ) ( O(1) space )
1,700
find-all-duplicates-in-an-array
0.734
junaidmansuri
Medium
7,818
442
string compression
class Solution: def compress(self, chars: List[str]) -> int: if not chars: return 0 mychar = chars[0] count = 0 length = len(chars) chars.append(" ") # Append a space so last char group is not left out in loop for i in range(length+1): #+1 for extra space char we added char = chars.pop(0) if char == mychar: #if same character then just increase the count count += 1 else: if count == 1: #if not same then append the char to chars chars.append(mychar) #if count is 1 don't append count elif count > 1: chars.append(mychar) chars += (list(str(count))) #if count > 1 append count as a string mychar = char #update mychar as the new different char in chars count = 1 #reset count to 1 as we have already read the new char return len(chars) #since all previous are popped, only the answer remains in chars now
https://leetcode.com/problems/string-compression/discuss/1025555/Python3-Simple-and-Intuitive
10
Given an array of characters chars, compress it using the following algorithm: Begin with an empty string s. For each group of consecutive repeating characters in chars: If the group's length is 1, append the character to s. Otherwise, append the character followed by the group's length. The compressed string s should not be returned separately, but instead, be stored in the input character array chars. Note that group lengths that are 10 or longer will be split into multiple characters in chars. After you are done modifying the input array, return the new length of the array. You must write an algorithm that uses only constant extra space. Example 1: Input: chars = ["a","a","b","b","c","c","c"] Output: Return 6, and the first 6 characters of the input array should be: ["a","2","b","2","c","3"] Explanation: The groups are "aa", "bb", and "ccc". This compresses to "a2b2c3". Example 2: Input: chars = ["a"] Output: Return 1, and the first character of the input array should be: ["a"] Explanation: The only group is "a", which remains uncompressed since it's a single character. Example 3: Input: chars = ["a","b","b","b","b","b","b","b","b","b","b","b","b"] Output: Return 4, and the first 4 characters of the input array should be: ["a","b","1","2"]. Explanation: The groups are "a" and "bbbbbbbbbbbb". This compresses to "ab12". Constraints: 1 <= chars.length <= 2000 chars[i] is a lowercase English letter, uppercase English letter, digit, or symbol.
Python3 Simple and Intuitive
1,800
string-compression
0.489
upenj
Medium
7,866
443
add two numbers ii
class Solution: def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode: n1 = n2 = 0 ptr1, ptr2 = l1, l2 stack = [] while ptr1: n1 += 1; ptr1 = ptr1.next while ptr2: n2 += 1; ptr2 = ptr2.next max_len = max(n1, n2) while max_len: a = b = 0 if max_len <= n1: a = l1.val; l1 = l1.next if max_len <= n2: b = l2.val; l2 = l2.next stack.append(a + b) max_len -= 1 sumval, head = 0, None while stack or sumval: if stack: sumval += stack.pop() node = ListNode(sumval % 10) node.next = head head = node sumval //= 10 return head
https://leetcode.com/problems/add-two-numbers-ii/discuss/486730/Python-Using-One-Stack-Memory-Usage%3A-Less-than-100
11
You are given two non-empty linked lists representing two non-negative integers. The most significant digit comes first and each of their nodes contains a single digit. Add the two numbers and return the sum as a linked list. You may assume the two numbers do not contain any leading zero, except the number 0 itself. Example 1: Input: l1 = [7,2,4,3], l2 = [5,6,4] Output: [7,8,0,7] Example 2: Input: l1 = [2,4,3], l2 = [5,6,4] Output: [8,0,7] Example 3: Input: l1 = [0], l2 = [0] Output: [0] Constraints: The number of nodes in each linked list is in the range [1, 100]. 0 <= Node.val <= 9 It is guaranteed that the list represents a number that does not have leading zeros. Follow up: Could you solve it without reversing the input lists?
Python - Using One Stack [Memory Usage: Less than 100%]
766
add-two-numbers-ii
0.595
mmbhatk
Medium
7,889
445
arithmetic slices ii subsequence
class Solution: def numberOfArithmeticSlices(self, nums: List[int]) -> int: ans = 0 freq = [defaultdict(int) for _ in range(len(nums))] # arithmetic sub-seqs for i, x in enumerate(nums): for ii in range(i): diff = x - nums[ii] ans += freq[ii].get(diff, 0) freq[i][diff] += 1 + freq[ii][diff] return ans
https://leetcode.com/problems/arithmetic-slices-ii-subsequence/discuss/1292744/Python3-freq-tables
2
Given an integer array nums, return the number of all the arithmetic subsequences of nums. A sequence of numbers is called arithmetic if it consists of at least three elements and if the difference between any two consecutive elements is the same. For example, [1, 3, 5, 7, 9], [7, 7, 7, 7], and [3, -1, -5, -9] are arithmetic sequences. For example, [1, 1, 2, 5, 7] is not an arithmetic sequence. A subsequence of an array is a sequence that can be formed by removing some elements (possibly none) of the array. For example, [2,5,10] is a subsequence of [1,2,1,2,4,1,5,10]. The test cases are generated so that the answer fits in 32-bit integer. Example 1: Input: nums = [2,4,6,8,10] Output: 7 Explanation: All arithmetic subsequence slices are: [2,4,6] [4,6,8] [6,8,10] [2,4,6,8] [4,6,8,10] [2,4,6,8,10] [2,6,10] Example 2: Input: nums = [7,7,7,7,7] Output: 16 Explanation: Any subsequence of this array is arithmetic. Constraints: 1 <= nums.length <= 1000 -231 <= nums[i] <= 231 - 1
[Python3] freq tables
120
arithmetic-slices-ii-subsequence
0.399
ye15
Hard
7,914
446
number of boomerangs
class Solution: def numberOfBoomerangs(self, p: List[List[int]]) -> int: L, t = len(p), 0 D = [[0]*L for i in range(L)] for i in range(L): E = {} for j in range(L): if j > i: D[i][j] = D[j][i] = (p[j][0]-p[i][0])**2 + (p[j][1]-p[i][1])**2 E[D[i][j]] = E[D[i][j]] + 1 if D[i][j] in E else 1 t += sum(r*(r-1) for r in E.values()) return t - Junaid Mansuri (LeetCode ID)@hotmail.com
https://leetcode.com/problems/number-of-boomerangs/discuss/355205/Solution-in-Python-3
2
You are given n points in the plane that are all distinct, where points[i] = [xi, yi]. A boomerang is a tuple of points (i, j, k) such that the distance between i and j equals the distance between i and k (the order of the tuple matters). Return the number of boomerangs. Example 1: Input: points = [[0,0],[1,0],[2,0]] Output: 2 Explanation: The two boomerangs are [[1,0],[0,0],[2,0]] and [[1,0],[2,0],[0,0]]. Example 2: Input: points = [[1,1],[2,2],[3,3]] Output: 2 Example 3: Input: points = [[1,1]] Output: 0 Constraints: n == points.length 1 <= n <= 500 points[i].length == 2 -104 <= xi, yi <= 104 All the points are unique.
Solution in Python 3
847
number-of-boomerangs
0.547
junaidmansuri
Medium
7,917
447
find all numbers disappeared in an array
class Solution: def findDisappearedNumbers(self, nums: List[int]) -> List[int]: for n in nums: a = abs(n) - 1 if nums[a] > 0: nums[a] *= -1 return [i+1 for i in range(len(nums)) if nums[i] > 0]
https://leetcode.com/problems/find-all-numbers-disappeared-in-an-array/discuss/313703/Python-3
54
Given an array nums of n integers where nums[i] is in the range [1, n], return an array of all the integers in the range [1, n] that do not appear in nums. Example 1: Input: nums = [4,3,2,7,8,2,3,1] Output: [5,6] Example 2: Input: nums = [1,1] Output: [2] Constraints: n == nums.length 1 <= n <= 105 1 <= nums[i] <= n Follow up: Could you do it without extra space and in O(n) runtime? You may assume the returned list does not count as extra space.
Python 3
7,900
find-all-numbers-disappeared-in-an-array
0.597
slight_edge
Easy
7,919
448
delete node in a bst
class Solution: def deleteNode(self, root: TreeNode, key: int) -> TreeNode: if not root: return None if root.val > key: # Target node is smaller than currnet node, search left subtree root.left = self.deleteNode( root.left, key ) elif root.val < key: # Target node is larger than currnet node, search right subtree root.right = self.deleteNode( root.right, key ) else: # Current node is target node if (not root.left) or (not root.right): # At least one child is empty # Target node is replaced by either non-empty child or None root = root.left if root.left else root.right else: # Both two childs exist # Target node is replaced by smallest element of right subtree cur = root.right while cur.left: cur = cur.left root.val = cur.val root.right = self.deleteNode( root.right, cur.val ) return root
https://leetcode.com/problems/delete-node-in-a-bst/discuss/543124/Python-O(-h-)-with-BST-property.-85%2B-w-Comment
8
Given a root node reference of a BST and a key, delete the node with the given key in the BST. Return the root node reference (possibly updated) of the BST. Basically, the deletion can be divided into two stages: Search for a node to remove. If the node is found, delete the node. Example 1: Input: root = [5,3,6,2,4,null,7], key = 3 Output: [5,4,6,2,null,null,7] Explanation: Given key to delete is 3. So we find the node with value 3 and delete it. One valid answer is [5,4,6,2,null,null,7], shown in the above BST. Please notice that another valid answer is [5,2,6,null,4,null,7] and it's also accepted. Example 2: Input: root = [5,3,6,2,4,null,7], key = 0 Output: [5,3,6,2,4,null,7] Explanation: The tree does not contain a node with value = 0. Example 3: Input: root = [], key = 0 Output: [] Constraints: The number of nodes in the tree is in the range [0, 104]. -105 <= Node.val <= 105 Each node has a unique value. root is a valid binary search tree. -105 <= key <= 105 Follow up: Could you solve it with time complexity O(height of tree)?
Python O( h ) with BST property. 85%+ [w/ Comment ]
605
delete-node-in-a-bst
0.5
brianchiang_tw
Medium
7,962
450
sort characters by frequency
class Solution: def frequencySort(self, s: str) -> str: ans_str = '' # Find unique characters characters = set(s) counts = [] # Count their frequency for i in characters: counts.append([i,s.count(i)]) # Sort characters according to their frequency counts = sorted(counts, key= lambda x: x[1], reverse = True) # Generate answer string by multiplying frequency count with the character for i,j in counts: ans_str += i*j return ans_str
https://leetcode.com/problems/sort-characters-by-frequency/discuss/1024318/Python3-Solution-or-24-MS-Runtime-or-15.2-MB-Memoryor-Easy-to-understand-solution
5
Given a string s, sort it in decreasing order based on the frequency of the characters. The frequency of a character is the number of times it appears in the string. Return the sorted string. If there are multiple answers, return any of them. Example 1: Input: s = "tree" Output: "eert" Explanation: 'e' appears twice while 'r' and 't' both appear once. So 'e' must appear before both 'r' and 't'. Therefore "eetr" is also a valid answer. Example 2: Input: s = "cccaaa" Output: "aaaccc" Explanation: Both 'c' and 'a' appear three times, so both "cccaaa" and "aaaccc" are valid answers. Note that "cacaca" is incorrect, as the same characters must be together. Example 3: Input: s = "Aabb" Output: "bbAa" Explanation: "bbaA" is also a valid answer, but "Aabb" is incorrect. Note that 'A' and 'a' are treated as two different characters. Constraints: 1 <= s.length <= 5 * 105 s consists of uppercase and lowercase English letters and digits.
Python3 Solution | 24 MS Runtime | 15.2 MB Memory| Easy to understand solution
401
sort-characters-by-frequency
0.686
dakshal33
Medium
7,984
451
minimum number of arrows to burst balloons
class Solution: def findMinArrowShots(self, points: List[List[int]]) -> int: pts = sorted(points, key=lambda el: el[1]) res, combo = 0, (float("-inf"), float("-inf")) for start, end in pts: if start <= combo[1]: # overlaps? combo = (max(combo[0], start), min(combo[1], end)) else: combo = (start, end) res += 1 return res
https://leetcode.com/problems/minimum-number-of-arrows-to-burst-balloons/discuss/1686588/Python3-COMBO-Explained
9
There are some spherical balloons taped onto a flat wall that represents the XY-plane. The balloons are represented as a 2D integer array points where points[i] = [xstart, xend] denotes a balloon whose horizontal diameter stretches between xstart and xend. You do not know the exact y-coordinates of the balloons. Arrows can be shot up directly vertically (in the positive y-direction) from different points along the x-axis. A balloon with xstart and xend is burst by an arrow shot at x if xstart <= x <= xend. There is no limit to the number of arrows that can be shot. A shot arrow keeps traveling up infinitely, bursting any balloons in its path. Given the array points, return the minimum number of arrows that must be shot to burst all balloons. Example 1: Input: points = [[10,16],[2,8],[1,6],[7,12]] Output: 2 Explanation: The balloons can be burst by 2 arrows: - Shoot an arrow at x = 6, bursting the balloons [2,8] and [1,6]. - Shoot an arrow at x = 11, bursting the balloons [10,16] and [7,12]. Example 2: Input: points = [[1,2],[3,4],[5,6],[7,8]] Output: 4 Explanation: One arrow needs to be shot for each balloon for a total of 4 arrows. Example 3: Input: points = [[1,2],[2,3],[3,4],[4,5]] Output: 2 Explanation: The balloons can be burst by 2 arrows: - Shoot an arrow at x = 2, bursting the balloons [1,2] and [2,3]. - Shoot an arrow at x = 4, bursting the balloons [3,4] and [4,5]. Constraints: 1 <= points.length <= 105 points[i].length == 2 -231 <= xstart < xend <= 231 - 1
✔️ [Python3] ➵ COMBO 🌸, Explained
290
minimum-number-of-arrows-to-burst-balloons
0.532
artod
Medium
8,027
452
minimum moves to equal array elements
class Solution: def minMoves(self, nums: List[int]) -> int: return sum(nums) - (len(nums) * min(nums))
https://leetcode.com/problems/minimum-moves-to-equal-array-elements/discuss/1909521/1-line-solution-beats-98-O(N)-time-and-96-O(1)-space-easy-to-understand
10
Given an integer array nums of size n, return the minimum number of moves required to make all array elements equal. In one move, you can increment n - 1 elements of the array by 1. Example 1: Input: nums = [1,2,3] Output: 3 Explanation: Only three moves are needed (remember each move increments two elements): [1,2,3] => [2,3,3] => [3,4,3] => [4,4,4] Example 2: Input: nums = [1,1,1] Output: 0 Constraints: n == nums.length 1 <= nums.length <= 105 -109 <= nums[i] <= 109 The answer is guaranteed to fit in a 32-bit integer.
1 line solution; beats 98% O(N) time and 96% O(1) space; easy to understand
461
minimum-moves-to-equal-array-elements
0.557
sahajamatya
Medium
8,053
453
4sum ii
class Solution: def fourSumCount(self, nums1: List[int], nums2: List[int], nums3: List[int], nums4: List[int]) -> int: # hashmap and final result count nums12, res = defaultdict(int), 0 # storing all possible combinations of sum for i in nums1: for j in nums2: nums12[i+j] += 1 # iterating the left out two array to find negation of same value for k in nums3: for l in nums4: res += nums12[-(k+l)] return res
https://leetcode.com/problems/4sum-ii/discuss/1741072/Python-Clean-and-concise-or-Detail-explanation-or-One-linear
19
Given four integer arrays nums1, nums2, nums3, and nums4 all of length n, return the number of tuples (i, j, k, l) such that: 0 <= i, j, k, l < n nums1[i] + nums2[j] + nums3[k] + nums4[l] == 0 Example 1: Input: nums1 = [1,2], nums2 = [-2,-1], nums3 = [-1,2], nums4 = [0,2] Output: 2 Explanation: The two tuples are: 1. (0, 0, 0, 1) -> nums1[0] + nums2[0] + nums3[0] + nums4[1] = 1 + (-2) + (-1) + 2 = 0 2. (1, 1, 0, 0) -> nums1[1] + nums2[1] + nums3[0] + nums4[0] = 2 + (-1) + (-1) + 0 = 0 Example 2: Input: nums1 = [0], nums2 = [0], nums3 = [0], nums4 = [0] Output: 1 Constraints: n == nums1.length n == nums2.length n == nums3.length n == nums4.length 1 <= n <= 200 -228 <= nums1[i], nums2[i], nums3[i], nums4[i] <= 228
[Python] Clean and concise | Detail explanation | One linear
939
4sum-ii
0.573
sidheshwar_s
Medium
8,069
454
assign cookies
class Solution: def findContentChildren(self, g: List[int], s: List[int]) -> int: g.sort() # O(nlogn) s.sort() # O(nlogn) child_point = 0 cookie_point = 0 counter = 0 # O(n) while child_point < len(g) and cookie_point < len(s): if g[child_point] <= s[cookie_point]: counter += 1 child_point += 1 cookie_point += 1 else: cookie_point += 1 return counter
https://leetcode.com/problems/assign-cookies/discuss/1334075/Python-Solution-or-Two-Pointers-or-O(nlogn)
2
Assume you are an awesome parent and want to give your children some cookies. But, you should give each child at most one cookie. Each child i has a greed factor g[i], which is the minimum size of a cookie that the child will be content with; and each cookie j has a size s[j]. If s[j] >= g[i], we can assign the cookie j to the child i, and the child i will be content. Your goal is to maximize the number of your content children and output the maximum number. Example 1: Input: g = [1,2,3], s = [1,1] Output: 1 Explanation: You have 3 children and 2 cookies. The greed factors of 3 children are 1, 2, 3. And even though you have 2 cookies, since their size is both 1, you could only make the child whose greed factor is 1 content. You need to output 1. Example 2: Input: g = [1,2], s = [1,2,3] Output: 2 Explanation: You have 2 children and 3 cookies. The greed factors of 2 children are 1, 2. You have 3 cookies and their sizes are big enough to gratify all of the children, You need to output 2. Constraints: 1 <= g.length <= 3 * 104 0 <= s.length <= 3 * 104 1 <= g[i], s[j] <= 231 - 1
Python Solution | Two Pointers | O(nlogn)
267
assign-cookies
0.505
peatear-anthony
Easy
8,099
455
132 pattern
class Solution: def find132pattern(self, nums: List[int]) -> bool: if len(nums)<3: return False second_num = -math.inf stck = [] # Try to find nums[i] < second_num < stck[-1] for i in range(len(nums) - 1, -1, -1): if nums[i] < second_num: return True # always ensure stack can be popped in increasing order while stck and stck[-1] < nums[i]: second_num = stck.pop() # this will ensure second_num < stck[-1] for next iteration stck.append(nums[i]) return False
https://leetcode.com/problems/132-pattern/discuss/2015125/Python-Solution-using-Stack
37
Given an array of n integers nums, a 132 pattern is a subsequence of three integers nums[i], nums[j] and nums[k] such that i < j < k and nums[i] < nums[k] < nums[j]. Return true if there is a 132 pattern in nums, otherwise, return false. Example 1: Input: nums = [1,2,3,4] Output: false Explanation: There is no 132 pattern in the sequence. Example 2: Input: nums = [3,1,4,2] Output: true Explanation: There is a 132 pattern in the sequence: [1, 4, 2]. Example 3: Input: nums = [-1,3,2,0] Output: true Explanation: There are three 132 patterns in the sequence: [-1, 3, 2], [-1, 3, 0] and [-1, 2, 0]. Constraints: n == nums.length 1 <= n <= 2 * 105 -109 <= nums[i] <= 109
✅ Python Solution using Stack
3,400
132-pattern
0.325
constantine786
Medium
8,121
456
circular array loop
class Solution: def circularArrayLoop(self, nums: List[int]) -> bool: n, visited = len(nums), set() for i in range(n): if i not in visited: local_s = set() while True: if i in local_s: return True if i in visited: break # credit to @crazyhyz, add this condition to avoid revisited visited.add(i) local_s.add(i) prev, i = i, (i + nums[i]) % n if prev == i or (nums[i] > 0) != (nums[prev] > 0): break return False
https://leetcode.com/problems/circular-array-loop/discuss/1317119/Python-3-or-Short-Python-Set-or-Explanation
10
You are playing a game involving a circular array of non-zero integers nums. Each nums[i] denotes the number of indices forward/backward you must move if you are located at index i: If nums[i] is positive, move nums[i] steps forward, and If nums[i] is negative, move nums[i] steps backward. Since the array is circular, you may assume that moving forward from the last element puts you on the first element, and moving backwards from the first element puts you on the last element. A cycle in the array consists of a sequence of indices seq of length k where: Following the movement rules above results in the repeating index sequence seq[0] -> seq[1] -> ... -> seq[k - 1] -> seq[0] -> ... Every nums[seq[j]] is either all positive or all negative. k > 1 Return true if there is a cycle in nums, or false otherwise. Example 1: Input: nums = [2,-1,1,2,2] Output: true Explanation: The graph shows how the indices are connected. White nodes are jumping forward, while red is jumping backward. We can see the cycle 0 --> 2 --> 3 --> 0 --> ..., and all of its nodes are white (jumping in the same direction). Example 2: Input: nums = [-1,-2,-3,-4,-5,6] Output: false Explanation: The graph shows how the indices are connected. White nodes are jumping forward, while red is jumping backward. The only cycle is of size 1, so we return false. Example 3: Input: nums = [1,-1,5,1,4] Output: true Explanation: The graph shows how the indices are connected. White nodes are jumping forward, while red is jumping backward. We can see the cycle 0 --> 1 --> 0 --> ..., and while it is of size > 1, it has a node jumping forward and a node jumping backward, so it is not a cycle. We can see the cycle 3 --> 4 --> 3 --> ..., and all of its nodes are white (jumping in the same direction). Constraints: 1 <= nums.length <= 5000 -1000 <= nums[i] <= 1000 nums[i] != 0 Follow up: Could you solve it in O(n) time complexity and O(1) extra space complexity?
Python 3 | Short Python, Set | Explanation
1,200
circular-array-loop
0.323
idontknoooo
Medium
8,141
457
poor pigs
class Solution: def poorPigs(self, buckets: int, minutesToDie: int, minutesToTest: int) -> int: return ceil(log(buckets) / log(minutesToTest / minutesToDie + 1));
https://leetcode.com/problems/poor-pigs/discuss/935581/C%2B%2BPythonPicture-1-line-greedy-solution-with-N-dimension-puzzle-cube-scan
34
There are buckets buckets of liquid, where exactly one of the buckets is poisonous. To figure out which one is poisonous, you feed some number of (poor) pigs the liquid to see whether they will die or not. Unfortunately, you only have minutesToTest minutes to determine which bucket is poisonous. You can feed the pigs according to these steps: Choose some live pigs to feed. For each pig, choose which buckets to feed it. The pig will consume all the chosen buckets simultaneously and will take no time. Each pig can feed from any number of buckets, and each bucket can be fed from by any number of pigs. Wait for minutesToDie minutes. You may not feed any other pigs during this time. After minutesToDie minutes have passed, any pigs that have been fed the poisonous bucket will die, and all others will survive. Repeat this process until you run out of time. Given buckets, minutesToDie, and minutesToTest, return the minimum number of pigs needed to figure out which bucket is poisonous within the allotted time. Example 1: Input: buckets = 4, minutesToDie = 15, minutesToTest = 15 Output: 2 Explanation: We can determine the poisonous bucket as follows: At time 0, feed the first pig buckets 1 and 2, and feed the second pig buckets 2 and 3. At time 15, there are 4 possible outcomes: - If only the first pig dies, then bucket 1 must be poisonous. - If only the second pig dies, then bucket 3 must be poisonous. - If both pigs die, then bucket 2 must be poisonous. - If neither pig dies, then bucket 4 must be poisonous. Example 2: Input: buckets = 4, minutesToDie = 15, minutesToTest = 30 Output: 2 Explanation: We can determine the poisonous bucket as follows: At time 0, feed the first pig bucket 1, and feed the second pig bucket 2. At time 15, there are 2 possible outcomes: - If either pig dies, then the poisonous bucket is the one it was fed. - If neither pig dies, then feed the first pig bucket 3, and feed the second pig bucket 4. At time 30, one of the two pigs must die, and the poisonous bucket is the one it was fed. Constraints: 1 <= buckets <= 1000 1 <= minutesToDie <= minutesToTest <= 100
[C++/Python/Picture] 1-line greedy solution with N-dimension puzzle cube scan
3,400
poor-pigs
0.643
codedayday
Hard
8,151
458
repeated substring pattern
class Solution: def repeatedSubstringPattern(self, s: str) -> bool: return s in s[1:] + s[:-1]
https://leetcode.com/problems/repeated-substring-pattern/discuss/2304034/Python-93.74-fasters-or-Python-Simplest-Solution-With-Explanation-or-Beg-to-adv-or-Slicing
6
Given a string s, check if it can be constructed by taking a substring of it and appending multiple copies of the substring together. Example 1: Input: s = "abab" Output: true Explanation: It is the substring "ab" twice. Example 2: Input: s = "aba" Output: false Example 3: Input: s = "abcabcabcabc" Output: true Explanation: It is the substring "abc" four times or the substring "abcabc" twice. Constraints: 1 <= s.length <= 104 s consists of lowercase English letters.
Python 93.74% fasters | Python Simplest Solution With Explanation | Beg to adv | Slicing
332
repeated-substring-pattern
0.437
rlakshay14
Easy
8,155
459
hamming distance
class Solution: def hammingDistance(self, x: int, y: int) -> int: def get_bin(num): res = [] while num > 0: res.append(num % 2) num //= 2 return ''.join(str(num) for num in res[::-1]) if x < y: x, y = y, x bin_x, bin_y = get_bin(x), get_bin(y) res = 0 s1, s2 = len(bin_x), len(bin_y) bin_y = '0' * (s1 - s2) + bin_y return sum(bin_x[i] != bin_y[i] for i in range(s1))
https://leetcode.com/problems/hamming-distance/discuss/1585601/Handmade-binary-function-(time%3A-O(L))
3
The Hamming distance between two integers is the number of positions at which the corresponding bits are different. Given two integers x and y, return the Hamming distance between them. Example 1: Input: x = 1, y = 4 Output: 2 Explanation: 1 (0 0 0 1) 4 (0 1 0 0) ↑ ↑ The above arrows point to positions where the corresponding bits are different. Example 2: Input: x = 3, y = 1 Output: 1 Constraints: 0 <= x, y <= 231 - 1
Handmade binary function (time: O(L))
121
hamming-distance
0.749
kryuki
Easy
8,184
461
minimum moves to equal array elements ii
class Solution: def minMoves2(self, nums: List[int]) -> int: nums.sort() mid = nums[len(nums)//2] result = 0 for i in nums: result+=abs(mid-i) return result
https://leetcode.com/problems/minimum-moves-to-equal-array-elements-ii/discuss/2218363/Python3-simple-solution%3A-Get-the-mid-element-from-the-sorted-array
6
Given an integer array nums of size n, return the minimum number of moves required to make all array elements equal. In one move, you can increment or decrement an element of the array by 1. Test cases are designed so that the answer will fit in a 32-bit integer. Example 1: Input: nums = [1,2,3] Output: 2 Explanation: Only two moves are needed (remember each move increments or decrements one element): [1,2,3] => [2,2,3] => [2,2,2] Example 2: Input: nums = [1,10,2,9] Output: 16 Constraints: n == nums.length 1 <= nums.length <= 105 -109 <= nums[i] <= 109
📌 Python3 simple solution: Get the mid element from the sorted array
68
minimum-moves-to-equal-array-elements-ii
0.602
Dark_wolf_jss
Medium
8,223
462
island perimeter
class Solution: def islandPerimeter(self, grid: List[List[int]]) -> int: M, N, p = len(grid), len(grid[0]), 0 for m in range(M): for n in range(N): if grid[m][n] == 1: if m == 0 or grid[m-1][n] == 0: p += 1 if n == 0 or grid[m][n-1] == 0: p += 1 if n == N-1 or grid[m][n+1] == 0: p += 1 if m == M-1 or grid[m+1][n] == 0: p += 1 return p - Junaid Mansuri - Chicago, IL
https://leetcode.com/problems/island-perimeter/discuss/343154/Solution-in-Python-3
36
You are given row x col grid representing a map where grid[i][j] = 1 represents land and grid[i][j] = 0 represents water. Grid cells are connected horizontally/vertically (not diagonally). The grid is completely surrounded by water, and there is exactly one island (i.e., one or more connected land cells). The island doesn't have "lakes", meaning the water inside isn't connected to the water around the island. One cell is a square with side length 1. The grid is rectangular, width and height don't exceed 100. Determine the perimeter of the island. Example 1: Input: grid = [[0,1,0,0],[1,1,1,0],[0,1,0,0],[1,1,0,0]] Output: 16 Explanation: The perimeter is the 16 yellow stripes in the image above. Example 2: Input: grid = [[1]] Output: 4 Example 3: Input: grid = [[1,0]] Output: 4 Constraints: row == grid.length col == grid[i].length 1 <= row, col <= 100 grid[i][j] is 0 or 1. There is exactly one island in grid.
Solution in Python 3
3,200
island-perimeter
0.695
junaidmansuri
Easy
8,271
463
can i win
class Solution: def canIWin(self, maxChoosableInteger: int, desiredTotal: int) -> bool: if desiredTotal == 0: return True # edge case 1 if maxChoosableInteger * (maxChoosableInteger+1)//2 < desiredTotal: return False # edge case 2 @lru_cache(None) def fn(mask, total): """Return True if there is a winning strategy given mask &amp; total.""" if total <= 0: return False # already lost for i in range(maxChoosableInteger): if mask &amp; (1 << i): # integer i+1 is not used yet if not fn(mask ^ (1 << i), total - (i + 1)): return True return False return fn(int("1"*maxChoosableInteger, 2), desiredTotal)
https://leetcode.com/problems/can-i-win/discuss/850051/Python3-top-down-dp
3
In the "100 game" two players take turns adding, to a running total, any integer from 1 to 10. The player who first causes the running total to reach or exceed 100 wins. What if we change the game so that players cannot re-use integers? For example, two players might take turns drawing from a common pool of numbers from 1 to 15 without replacement until they reach a total >= 100. Given two integers maxChoosableInteger and desiredTotal, return true if the first player to move can force a win, otherwise, return false. Assume both players play optimally. Example 1: Input: maxChoosableInteger = 10, desiredTotal = 11 Output: false Explanation: No matter which integer the first player choose, the first player will lose. The first player can choose an integer from 1 up to 10. If the first player choose 1, the second player can only choose integers from 2 up to 10. The second player will win by choosing 10 and get a total = 11, which is >= desiredTotal. Same with other integers chosen by the first player, the second player will always win. Example 2: Input: maxChoosableInteger = 10, desiredTotal = 0 Output: true Example 3: Input: maxChoosableInteger = 10, desiredTotal = 1 Output: true Constraints: 1 <= maxChoosableInteger <= 20 0 <= desiredTotal <= 300
[Python3] top-down dp
423
can-i-win
0.298
ye15
Medium
8,316
464
count the repetitions
class Solution: def getMaxRepetitions(self, s1: str, n1: int, s2: str, n2: int) -> int: cnt = idx = 0 count = [] index = [] for i in range(n1): for ch in s1: if ch == s2[idx]: idx += 1 if idx == len(s2): cnt += 1 idx = 0 count.append(cnt) index.append(idx) for ii in range(i): if index[ii] == idx: prev = count[ii] repeat = (cnt - prev) * ((n1-1-ii) // (i - ii)) post = count[ii + (n1-1-ii) % (i-ii)] - count[ii] return (prev + repeat + post) // n2 return count[-1]//n2
https://leetcode.com/problems/count-the-repetitions/discuss/2521184/Python3-repeating-patterns
0
We define str = [s, n] as the string str which consists of the string s concatenated n times. For example, str == ["abc", 3] =="abcabcabc". We define that string s1 can be obtained from string s2 if we can remove some characters from s2 such that it becomes s1. For example, s1 = "abc" can be obtained from s2 = "abdbec" based on our definition by removing the bolded underlined characters. You are given two strings s1 and s2 and two integers n1 and n2. You have the two strings str1 = [s1, n1] and str2 = [s2, n2]. Return the maximum integer m such that str = [str2, m] can be obtained from str1. Example 1: Input: s1 = "acb", n1 = 4, s2 = "ab", n2 = 2 Output: 2 Example 2: Input: s1 = "acb", n1 = 1, s2 = "acb", n2 = 1 Output: 1 Constraints: 1 <= s1.length, s2.length <= 100 s1 and s2 consist of lowercase English letters. 1 <= n1, n2 <= 106
[Python3] repeating patterns
22
count-the-repetitions
0.293
ye15
Hard
8,321
466
unique substrings in wraparound string
class Solution: def findSubstringInWraproundString(self, p: str) -> int: consecutive = 1 # stores the maximum length of a substring ending at a character maxSubstr = defaultdict(int) maxSubstr[p[0]] = 1 ans = 0 for x in range(1, len(p)): if ord(p[x]) - ord(p[x - 1]) == 1 or p[x] == 'a' and p[x - 1] == 'z': consecutive += 1 else: consecutive = 1 maxSubstr[p[x]] = max(maxSubstr[p[x]], consecutive) return sum(maxSubstr.values())
https://leetcode.com/problems/unique-substrings-in-wraparound-string/discuss/1705570/Python3-DP-O(N)-time-O(1)-space
1
We define the string base to be the infinite wraparound string of "abcdefghijklmnopqrstuvwxyz", so base will look like this: "...zabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcd....". Given a string s, return the number of unique non-empty substrings of s are present in base. Example 1: Input: s = "a" Output: 1 Explanation: Only the substring "a" of s is in base. Example 2: Input: s = "cac" Output: 2 Explanation: There are two substrings ("a", "c") of s in base. Example 3: Input: s = "zab" Output: 6 Explanation: There are six substrings ("z", "a", "b", "za", "ab", and "zab") of s in base. Constraints: 1 <= s.length <= 105 s consists of lowercase English letters.
Python3 DP O(N) time O(1) space
92
unique-substrings-in-wraparound-string
0.383
srihariv
Medium
8,322
467
validate ip address
class Solution: def validIPAddress(self, query: str) -> str: dot = query.count(".") colon = query.count(":") if colon == 0 and dot == 3: arr = [i for i in query.split(".")] print(arr) flag = True for i in arr: if i.isdigit() and int(i) <= 255: x = int(i) if str(x) != i: flag = False break else: flag = False break if flag: return "IPv4" else: return "Neither" elif colon == 7 and dot == 0: flag = True arr = [i for i in query.split(":")] for parts in arr: l = 0 for i in parts: l += 1 if i not in "0123456789abcdefABCDEF": flag = False break if l > 4 or l < 1:flag = False;break if flag: return "IPv6" else: return "Neither" else: return "Neither"
https://leetcode.com/problems/validate-ip-address/discuss/2440773/Python-or-Easiest-solution-Faster-than-99-or-easy-if-and-else
0
Given a string queryIP, return "IPv4" if IP is a valid IPv4 address, "IPv6" if IP is a valid IPv6 address or "Neither" if IP is not a correct IP of any type. A valid IPv4 address is an IP in the form "x1.x2.x3.x4" where 0 <= xi <= 255 and xi cannot contain leading zeros. For example, "192.168.1.1" and "192.168.1.0" are valid IPv4 addresses while "192.168.01.1", "192.168.1.00", and "192.168@1.1" are invalid IPv4 addresses. A valid IPv6 address is an IP in the form "x1:x2:x3:x4:x5:x6:x7:x8" where: 1 <= xi.length <= 4 xi is a hexadecimal string which may contain digits, lowercase English letter ('a' to 'f') and upper-case English letters ('A' to 'F'). Leading zeros are allowed in xi. For example, "2001:0db8:85a3:0000:0000:8a2e:0370:7334" and "2001:db8:85a3:0:0:8A2E:0370:7334" are valid IPv6 addresses, while "2001:0db8:85a3::8A2E:037j:7334" and "02001:0db8:85a3:0000:0000:8a2e:0370:7334" are invalid IPv6 addresses. Example 1: Input: queryIP = "172.16.254.1" Output: "IPv4" Explanation: This is a valid IPv4 address, return "IPv4". Example 2: Input: queryIP = "2001:0db8:85a3:0:0:8A2E:0370:7334" Output: "IPv6" Explanation: This is a valid IPv6 address, return "IPv6". Example 3: Input: queryIP = "256.256.256.256" Output: "Neither" Explanation: This is neither a IPv4 address nor a IPv6 address. Constraints: queryIP consists only of English letters, digits and the characters '.' and ':'.
Python | Easiest solution Faster than 99% | easy if and else
134
validate-ip-address
0.266
sami2002
Medium
8,326
468
concatenated words
class Solution: def findAllConcatenatedWordsInADict(self, words: List[str]) -> List[str]: ddic = lambda: defaultdict(ddic) trie = ddic() for word in words: cur = trie for char in word: cur = cur[char] cur['end'] = True def isConcat(word, start): cur = trie for i in range(start, len(word)): char = word[i] if char not in cur: return False cur = cur[char] if 'end' in cur: if i + 1 == len(word): # tricky part that helps us distinguish simple word from concat word return start != 0 if isConcat(word, i + 1): return True return False return [word for word in words if isConcat(word, 0)]
https://leetcode.com/problems/concatenated-words/discuss/2189673/Python3-TRIE-WITH-RECURSION-(-)-Explained
4
Given an array of strings words (without duplicates), return all the concatenated words in the given list of words. A concatenated word is defined as a string that is comprised entirely of at least two shorter words (not necessarily distinct) in the given array. Example 1: Input: words = ["cat","cats","catsdogcats","dog","dogcatsdog","hippopotamuses","rat","ratcatdogcat"] Output: ["catsdogcats","dogcatsdog","ratcatdogcat"] Explanation: "catsdogcats" can be concatenated by "cats", "dog" and "cats"; "dogcatsdog" can be concatenated by "dog", "cats" and "dog"; "ratcatdogcat" can be concatenated by "rat", "cat", "dog" and "cat". Example 2: Input: words = ["cat","dog","catdog"] Output: ["catdog"] Constraints: 1 <= words.length <= 104 1 <= words[i].length <= 30 words[i] consists of only lowercase English letters. All the strings of words are unique. 1 <= sum(words[i].length) <= 105
✔️ [Python3] TRIE WITH RECURSION ᕕ( ᐛ )ᕗ, Explained
100
concatenated-words
0.458
artod
Hard
8,332
472
matchsticks to square
class Solution: def makesquare(self, arr: List[int]) -> bool: # no way to make the square if total length not divisble by 4 if sum(arr) % 4: return False # target side length side = sum(arr) // 4 @lru_cache(None) def dp(k, mask, s): # finish all four sides if k == 4: return True # move on to next side if current one finished if not s: return dp(k+1, mask, side) for i in range(len(arr)): # if current matchstick used or longer than remaining side length to fill then skip if mask &amp; (1 << i) or s < arr[i]: continue if dp(k, mask ^ (1 << i), s - arr[i]): return True return False return dp(0, 0, side)
https://leetcode.com/problems/matchsticks-to-square/discuss/2270373/Python-3DP-%2B-Bitmask
6
You are given an integer array matchsticks where matchsticks[i] is the length of the ith matchstick. You want to use all the matchsticks to make one square. You should not break any stick, but you can link them up, and each matchstick must be used exactly one time. Return true if you can make this square and false otherwise. Example 1: Input: matchsticks = [1,1,2,2,2] Output: true Explanation: You can form a square with length 2, one side of the square came two sticks with length 1. Example 2: Input: matchsticks = [3,3,3,3,4] Output: false Explanation: You cannot find a way to form a square with all the matchsticks. Constraints: 1 <= matchsticks.length <= 15 1 <= matchsticks[i] <= 108
[Python 3]DP + Bitmask
662
matchsticks-to-square
0.404
chestnut890123
Medium
8,344
473
ones and zeroes
class Solution: def findMaxForm(self, strs: List[str], m: int, n: int) -> int: counter=[[s.count("0"), s.count("1")] for s in strs] @cache def dp(i,j,idx): if i<0 or j<0: return -math.inf if idx==len(strs): return 0 return max(dp(i,j,idx+1), 1 + dp(i-counter[idx][0], j-counter[idx][1], idx+1)) return dp(m,n,0)
https://leetcode.com/problems/ones-and-zeroes/discuss/2065208/Python-Easy-DP-2-approaches
71
You are given an array of binary strings strs and two integers m and n. Return the size of the largest subset of strs such that there are at most m 0's and n 1's in the subset. A set x is a subset of a set y if all elements of x are also elements of y. Example 1: Input: strs = ["10","0001","111001","1","0"], m = 5, n = 3 Output: 4 Explanation: The largest subset with at most 5 0's and 3 1's is {"10", "0001", "1", "0"}, so the answer is 4. Other valid but smaller subsets include {"0001", "1"} and {"10", "1", "0"}. {"111001"} is an invalid subset because it contains 4 1's, greater than the maximum of 3. Example 2: Input: strs = ["10","0","1"], m = 1, n = 1 Output: 2 Explanation: The largest subset is {"0", "1"}, so the answer is 2. Constraints: 1 <= strs.length <= 600 1 <= strs[i].length <= 100 strs[i] consists only of digits '0' and '1'. 1 <= m, n <= 100
Python Easy DP 2 approaches
4,300
ones-and-zeroes
0.467
constantine786
Medium
8,360
474
heaters
class Solution: def findRadius(self, houses: List[int], heaters: List[int]) -> int: houses.sort() heaters.sort() if len(heaters) == 1: return max(abs(houses[0] - heaters[0]), abs(houses[-1] - heaters[0])) m_value = -1 f, s, ind_heat = heaters[0], heaters[1], 2 for i in range(len(houses)): while houses[i] > s and ind_heat < len(heaters): f, s = s, heaters[ind_heat] ind_heat += 1 m_value = max(m_value, min(abs(houses[i] - f), abs(houses[i] - s))) return m_value
https://leetcode.com/problems/heaters/discuss/2711430/python-99.84-speed-O(1)-memory
2
Winter is coming! During the contest, your first job is to design a standard heater with a fixed warm radius to warm all the houses. Every house can be warmed, as long as the house is within the heater's warm radius range. Given the positions of houses and heaters on a horizontal line, return the minimum radius standard of heaters so that those heaters could cover all houses. Notice that all the heaters follow your radius standard, and the warm radius will the same. Example 1: Input: houses = [1,2,3], heaters = [2] Output: 1 Explanation: The only heater was placed in the position 2, and if we use the radius 1 standard, then all the houses can be warmed. Example 2: Input: houses = [1,2,3,4], heaters = [1,4] Output: 1 Explanation: The two heaters were placed at positions 1 and 4. We need to use a radius 1 standard, then all the houses can be warmed. Example 3: Input: houses = [1,5], heaters = [2] Output: 3 Constraints: 1 <= houses.length, heaters.length <= 3 * 104 1 <= houses[i], heaters[i] <= 109
python 99.84% speed O(1) memory
234
heaters
0.361
Yaro1
Medium
8,383
475
number complement
class Solution: def findComplement(self, num: int) -> int: bit_mask = 2**num.bit_length() -1 return ( num ^ bit_mask )
https://leetcode.com/problems/number-complement/discuss/488055/Python-O(-lg-n-)-sol.-by-XOR-masking.-85%2B-With-explanation
17
The complement of an integer is the integer you get when you flip all the 0's to 1's and all the 1's to 0's in its binary representation. For example, The integer 5 is "101" in binary and its complement is "010" which is the integer 2. Given an integer num, return its complement. Example 1: Input: num = 5 Output: 2 Explanation: The binary representation of 5 is 101 (no leading zero bits), and its complement is 010. So you need to output 2. Example 2: Input: num = 1 Output: 0 Explanation: The binary representation of 1 is 1 (no leading zero bits), and its complement is 0. So you need to output 0. Constraints: 1 <= num < 231 Note: This question is the same as 1009: https://leetcode.com/problems/complement-of-base-10-integer/
Python O( lg n ) sol. by XOR masking. 85%+ [ With explanation ]
1,100
number-complement
0.672
brianchiang_tw
Easy
8,398
476
total hamming distance
class Solution: def totalHammingDistance(self, nums: List[int]) -> int: ans = 0 for i in range(32): zero = one = 0 mask = 1 << i for num in nums: if mask &amp; num: one += 1 else: zero += 1 ans += one * zero return ans
https://leetcode.com/problems/total-hamming-distance/discuss/851194/Python-3-or-Bit-Manipulation-O(N)-or-Explanations
26
The Hamming distance between two integers is the number of positions at which the corresponding bits are different. Given an integer array nums, return the sum of Hamming distances between all the pairs of the integers in nums. Example 1: Input: nums = [4,14,2] Output: 6 Explanation: In binary representation, the 4 is 0100, 14 is 1110, and 2 is 0010 (just showing the four bits relevant in this case). The answer will be: HammingDistance(4, 14) + HammingDistance(4, 2) + HammingDistance(14, 2) = 2 + 2 + 2 = 6. Example 2: Input: nums = [4,14,4] Output: 4 Constraints: 1 <= nums.length <= 104 0 <= nums[i] <= 109 The answer for the given input will fit in a 32-bit integer.
Python 3 | Bit Manipulation O(N) | Explanations
1,300
total-hamming-distance
0.522
idontknoooo
Medium
8,437
477
generate random point in a circle
class Solution: def __init__(self, radius: float, x_center: float, y_center: float): self.x = x_center self.y = y_center self.radius = radius def randPoint(self) -> List[float]: first = random.uniform(-self.radius, self.radius) secondmax = (self.radius ** 2 - first ** 2) ** 0.5 second = random.uniform(-secondmax, secondmax) return [self.x + first, self.y + second]
https://leetcode.com/problems/generate-random-point-in-a-circle/discuss/1113715/Python-wrong-test-cases
4
Given the radius and the position of the center of a circle, implement the function randPoint which generates a uniform random point inside the circle. Implement the Solution class: Solution(double radius, double x_center, double y_center) initializes the object with the radius of the circle radius and the position of the center (x_center, y_center). randPoint() returns a random point inside the circle. A point on the circumference of the circle is considered to be in the circle. The answer is returned as an array [x, y]. Example 1: Input ["Solution", "randPoint", "randPoint", "randPoint"] [[1.0, 0.0, 0.0], [], [], []] Output [null, [-0.02493, -0.38077], [0.82314, 0.38945], [0.36572, 0.17248]] Explanation Solution solution = new Solution(1.0, 0.0, 0.0); solution.randPoint(); // return [-0.02493, -0.38077] solution.randPoint(); // return [0.82314, 0.38945] solution.randPoint(); // return [0.36572, 0.17248] Constraints: 0 < radius <= 108 -107 <= x_center, y_center <= 107 At most 3 * 104 calls will be made to randPoint.
Python, wrong test cases?
322
generate-random-point-in-a-circle
0.396
warmr0bot
Medium
8,444
478
largest palindrome product
class Solution: def largestPalindrome(self, n: int) -> int: # just to forget about 1-digit case if n == 1: return 9 # minimal number with n digits (for ex. for n = 4, min_num = 1000) min_num = 10 ** (n - 1) # maximal number with n digits (for ex. 9999) max_num = 10 ** n - 1 max_pal = 0 # step is equal to 2, because we have to get a number, the 1st digit of which is 9, so we have to # iterate only over odd numbers for i in range(max_num, min_num - 1, -2): # since we are looking for the maximum palindrome number, it makes no sense to iterate over the # product less than the max_pal obtained from the last iteration if i * i < max_pal: break for j in range(max_num, i - 1, -2): product = i * j # since a palindrome with an even number of digits must be mod 11 == 0 and we have no reason to # check the product which less or equal than max_pal if product % 11 != 0 and product >= max_pal: continue # check if product is a palindrome then update the max_pal if str(product) == str(product)[::-1]: max_pal = product return max_pal % 1337
https://leetcode.com/problems/largest-palindrome-product/discuss/1521512/Python3-Solution-with-explanation
8
Given an integer n, return the largest palindromic integer that can be represented as the product of two n-digits integers. Since the answer can be very large, return it modulo 1337. Example 1: Input: n = 2 Output: 987 Explanation: 99 x 91 = 9009, 9009 % 1337 = 987 Example 2: Input: n = 1 Output: 9 Constraints: 1 <= n <= 8
Python3 Solution with explanation
741
largest-palindrome-product
0.317
frolovdmn
Hard
8,450
479
sliding window median
class Solution: # TC - O((n - k)*log(k)) # SC - O(k) # 121 ms, faster than 96.23% def find_median(self, max_heap, min_heap, heap_size): if heap_size % 2 == 1: return -max_heap[0] else: return (-max_heap[0] + min_heap[0]) / 2 def medianSlidingWindow(self, nums: List[int], k: int) -> List[float]: max_heap = [] min_heap = [] heap_dict = defaultdict(int) result = [] for i in range(k): heappush(max_heap, -nums[i]) heappush(min_heap, -heappop(max_heap)) if len(min_heap) > len(max_heap): heappush(max_heap, -heappop(min_heap)) median = self.find_median(max_heap, min_heap, k) result.append(median) for i in range(k, len(nums)): prev_num = nums[i - k] heap_dict[prev_num] += 1 balance = -1 if prev_num <= median else 1 if nums[i] <= median: balance += 1 heappush(max_heap, -nums[i]) else: balance -= 1 heappush(min_heap, nums[i]) if balance < 0: heappush(max_heap, -heappop(min_heap)) elif balance > 0: heappush(min_heap, -heappop(max_heap)) while max_heap and heap_dict[-max_heap[0]] > 0: heap_dict[-max_heap[0]] -= 1 heappop(max_heap) while min_heap and heap_dict[min_heap[0]] > 0: heap_dict[min_heap[0]] -= 1 heappop(min_heap) median = self.find_median(max_heap, min_heap, k) result.append(median) return result
https://leetcode.com/problems/sliding-window-median/discuss/1942580/Easiest-Python-O(n-log-k)-Two-Heaps-(Lazy-Removal)-96.23
4
The median is the middle value in an ordered integer list. If the size of the list is even, there is no middle value. So the median is the mean of the two middle values. For examples, if arr = [2,3,4], the median is 3. For examples, if arr = [1,2,3,4], the median is (2 + 3) / 2 = 2.5. You are given an integer array nums and an integer k. There is a sliding window of size k which is moving from the very left of the array to the very right. You can only see the k numbers in the window. Each time the sliding window moves right by one position. Return the median array for each window in the original array. Answers within 10-5 of the actual value will be accepted. Example 1: Input: nums = [1,3,-1,-3,5,3,6,7], k = 3 Output: [1.00000,-1.00000,-1.00000,3.00000,5.00000,6.00000] Explanation: Window position Median --------------- ----- [1 3 -1] -3 5 3 6 7 1 1 [3 -1 -3] 5 3 6 7 -1 1 3 [-1 -3 5] 3 6 7 -1 1 3 -1 [-3 5 3] 6 7 3 1 3 -1 -3 [5 3 6] 7 5 1 3 -1 -3 5 [3 6 7] 6 Example 2: Input: nums = [1,2,3,4,2,3,1,4,2], k = 3 Output: [2.00000,3.00000,3.00000,3.00000,2.00000,3.00000,2.00000] Constraints: 1 <= k <= nums.length <= 105 -231 <= nums[i] <= 231 - 1
✅ Easiest Python O(n log k) Two Heaps (Lazy Removal), 96.23%
480
sliding-window-median
0.414
AntonBelski
Hard
8,453
480
magical string
class Solution: def magicalString(self, n: int) -> int: arr, i = [1,2,2], 2 while len(arr) < n: arr.extend([arr[-1]^3]*arr[i]) i += 1 return arr[:n].count(1)
https://leetcode.com/problems/magical-string/discuss/2558509/481.-Magical-String
3
A magical string s consists of only '1' and '2' and obeys the following rules: The string s is magical because concatenating the number of contiguous occurrences of characters '1' and '2' generates the string s itself. The first few elements of s is s = "1221121221221121122……". If we group the consecutive 1's and 2's in s, it will be "1 22 11 2 1 22 1 22 11 2 11 22 ......" and the occurrences of 1's or 2's in each group are "1 2 2 1 1 2 1 2 2 1 2 2 ......". You can see that the occurrence sequence is s itself. Given an integer n, return the number of 1's in the first n number in the magical string s. Example 1: Input: n = 6 Output: 3 Explanation: The first 6 elements of magical string s is "122112" and it contains three 1's, so return 3. Example 2: Input: n = 1 Output: 1 Constraints: 1 <= n <= 105
481. Magical String
417
magical-string
0.505
warrenruud
Medium
8,460
481
license key formatting
class Solution: def licenseKeyFormatting(self, S: str, K: int) -> str: # Eliminate all dashes S = S.replace('-', '') head = len(S) % K grouping = [] # Special handle for first group if head: grouping.append( S[:head] ) # General case: for index in range(head, len(S), K ): grouping.append( S[ index : index+K ] ) # Link each group togetger and separated by dash '-' return '-'.join( grouping ).upper()
https://leetcode.com/problems/license-key-formatting/discuss/540266/PythonJSC%2B%2B-O(n)-by-string-operation.-w-Explanation
35
You are given a license key represented as a string s that consists of only alphanumeric characters and dashes. The string is separated into n + 1 groups by n dashes. You are also given an integer k. We want to reformat the string s such that each group contains exactly k characters, except for the first group, which could be shorter than k but still must contain at least one character. Furthermore, there must be a dash inserted between two groups, and you should convert all lowercase letters to uppercase. Return the reformatted license key. Example 1: Input: s = "5F3Z-2e-9-w", k = 4 Output: "5F3Z-2E9W" Explanation: The string s has been split into two parts, each part has 4 characters. Note that the two extra dashes are not needed and can be removed. Example 2: Input: s = "2-5g-3-J", k = 2 Output: "2-5G-3J" Explanation: The string s has been split into three parts, each part has 2 characters except the first part as it could be shorter as mentioned above. Constraints: 1 <= s.length <= 105 s consists of English letters, digits, and dashes '-'. 1 <= k <= 104
Python/JS/C++ O(n) by string operation. [w/ Explanation]
1,700
license-key-formatting
0.432
brianchiang_tw
Easy
8,466
482
smallest good base
class Solution: def smallestGoodBase(self, n: str) -> str: import math n = int(n) max_m = math.floor(math.log(n, 2)) ans = 0 for m in range(max_m, 0, -1): k = int(n ** (1 / m)) if (k ** (m + 1) - 1) // (k - 1) == n: return str(k) return str(n - 1)
https://leetcode.com/problems/smallest-good-base/discuss/2368982/faster-than-97.27-or-python
1
Given an integer n represented as a string, return the smallest good base of n. We call k >= 2 a good base of n, if all digits of n base k are 1's. Example 1: Input: n = "13" Output: "3" Explanation: 13 base 3 is 111. Example 2: Input: n = "4681" Output: "8" Explanation: 4681 base 8 is 11111. Example 3: Input: n = "1000000000000000000" Output: "999999999999999999" Explanation: 1000000000000000000 base 999999999999999999 is 11. Constraints: n is an integer in the range [3, 1018]. n does not contain any leading zeros.
faster than 97.27% | python
107
smallest-good-base
0.384
vimla_kushwaha
Hard
8,493
483
max consecutive ones
class Solution: def findMaxConsecutiveOnes(self, nums: List[int]) -> int: c1,c2=0,0 for i in nums: if i==1: c1+=1 elif i==0: c1=0 if c1>c2: c2=c1 return c2
https://leetcode.com/problems/max-consecutive-ones/discuss/1011637/Simple-and-easy-if-else-solution-faster-than-99.91
8
Given a binary array nums, return the maximum number of consecutive 1's in the array. Example 1: Input: nums = [1,1,0,1,1,1] Output: 3 Explanation: The first two digits or the last three digits are consecutive 1s. The maximum number of consecutive 1s is 3. Example 2: Input: nums = [1,0,1,1,0,1] Output: 2 Constraints: 1 <= nums.length <= 105 nums[i] is either 0 or 1.
Simple and easy if-else solution, faster than 99.91%
688
max-consecutive-ones
0.561
thisisakshat
Easy
8,495
485
predict the winner
class Solution: def PredictTheWinner(self, nums: List[int]) -> bool: def helper(i, j): if i == j: return nums[i] if (i, j) in memo: return memo[(i, j)] score = max(nums[j] - helper(i, j-1), nums[i] - helper(i+1, j)) memo[(i, j)] = score return score memo = {} return helper(0, len(nums)-1) >= 0
https://leetcode.com/problems/predict-the-winner/discuss/414803/Python-AC-98-Both-Recursion-and-DP-with-detailed-explanation.
19
You are given an integer array nums. Two players are playing a game with this array: player 1 and player 2. Player 1 and player 2 take turns, with player 1 starting first. Both players start the game with a score of 0. At each turn, the player takes one of the numbers from either end of the array (i.e., nums[0] or nums[nums.length - 1]) which reduces the size of the array by 1. The player adds the chosen number to their score. The game ends when there are no more elements in the array. Return true if Player 1 can win the game. If the scores of both players are equal, then player 1 is still the winner, and you should also return true. You may assume that both players are playing optimally. Example 1: Input: nums = [1,5,2] Output: false Explanation: Initially, player 1 can choose between 1 and 2. If he chooses 2 (or 1), then player 2 can choose from 1 (or 2) and 5. If player 2 chooses 5, then player 1 will be left with 1 (or 2). So, final score of player 1 is 1 + 2 = 3, and player 2 is 5. Hence, player 1 will never be the winner and you need to return false. Example 2: Input: nums = [1,5,233,7] Output: true Explanation: Player 1 first chooses 1. Then player 2 has to choose between 5 and 7. No matter which number player 2 choose, player 1 can choose 233. Finally, player 1 has more score (234) than player 2 (12), so you need to return True representing player1 can win. Constraints: 1 <= nums.length <= 20 0 <= nums[i] <= 107
Python [AC 98%] Both Recursion & DP with detailed explanation.
1,300
predict-the-winner
0.509
bos
Medium
8,546
486
zuma game
class Solution: def findMinStep(self, board: str, hand: str) -> int: # start from i and remove continues ball def remove_same(s, i): if i < 0: return s left = right = i while left > 0 and s[left-1] == s[i]: left -= 1 while right+1 < len(s) and s[right+1] == s[i]: right += 1 length = right - left + 1 if length >= 3: new_s = s[:left] + s[right+1:] return remove_same(new_s, left-1) else: return s hand = "".join(sorted(hand)) # board, hand and step q = collections.deque([(board, hand, 0)]) visited = set([(board, hand)]) while q: curr_board, curr_hand, step = q.popleft() for i in range(len(curr_board)+1): for j in range(len(curr_hand)): # skip the continue balls in hand if j > 0 and curr_hand[j] == curr_hand[j-1]: continue # only insert at the begin of continue balls in board if i > 0 and curr_board[i-1] == curr_hand[j]: # left side same color continue pick = False # 1. same color with right # 2. left and right are same but pick is different if i < len(curr_board) and curr_board[i] == curr_hand[j]: pick = True if 0<i<len(curr_board) and curr_board[i-1] == curr_board[i] and curr_board[i] != curr_hand[j]: pick = True if pick: new_board = remove_same(curr_board[:i] + curr_hand[j] + curr_board[i:], i) new_hand = curr_hand[:j] + curr_hand[j+1:] if not new_board: return step + 1 if (new_board, new_hand) not in visited: q.append((new_board, new_hand, step+1)) visited.add((new_board, new_hand)) return -1
https://leetcode.com/problems/zuma-game/discuss/1568450/Python-Easy-BFS-solution-with-explain
8
You are playing a variation of the game Zuma. In this variation of Zuma, there is a single row of colored balls on a board, where each ball can be colored red 'R', yellow 'Y', blue 'B', green 'G', or white 'W'. You also have several colored balls in your hand. Your goal is to clear all of the balls from the board. On each turn: Pick any ball from your hand and insert it in between two balls in the row or on either end of the row. If there is a group of three or more consecutive balls of the same color, remove the group of balls from the board. If this removal causes more groups of three or more of the same color to form, then continue removing each group until there are none left. If there are no more balls on the board, then you win the game. Repeat this process until you either win or do not have any more balls in your hand. Given a string board, representing the row of balls on the board, and a string hand, representing the balls in your hand, return the minimum number of balls you have to insert to clear all the balls from the board. If you cannot clear all the balls from the board using the balls in your hand, return -1. Example 1: Input: board = "WRRBBW", hand = "RB" Output: -1 Explanation: It is impossible to clear all the balls. The best you can do is: - Insert 'R' so the board becomes WRRRBBW. WRRRBBW -> WBBW. - Insert 'B' so the board becomes WBBBW. WBBBW -> WW. There are still balls remaining on the board, and you are out of balls to insert. Example 2: Input: board = "WWRRBBWW", hand = "WRBRW" Output: 2 Explanation: To make the board empty: - Insert 'R' so the board becomes WWRRRBBWW. WWRRRBBWW -> WWBBWW. - Insert 'B' so the board becomes WWBBBWW. WWBBBWW -> WWWW -> empty. 2 balls from your hand were needed to clear the board. Example 3: Input: board = "G", hand = "GGGGG" Output: 2 Explanation: To make the board empty: - Insert 'G' so the board becomes GG. - Insert 'G' so the board becomes GGG. GGG -> empty. 2 balls from your hand were needed to clear the board. Constraints: 1 <= board.length <= 16 1 <= hand.length <= 5 board and hand consist of the characters 'R', 'Y', 'B', 'G', and 'W'. The initial row of balls on the board will not have any groups of three or more consecutive balls of the same color.
[Python] Easy BFS solution with explain
634
zuma-game
0.346
nightybear
Hard
8,564
488
increasing subsequences
class Solution: def findSubsequences(self, nums: List[int]) -> List[List[int]]: def dfs(i, num, curr): if len(curr)>=2: ans.add(curr[:]) if i>=len(nums): return for j in range(i, len(nums)): if nums[j]>=num: dfs(j+1, nums[j], curr+(nums[j],)) ans = set() dfs(0, -float("inf"), ()) return ans
https://leetcode.com/problems/increasing-subsequences/discuss/1577928/Python-DFS
3
Given an integer array nums, return all the different possible non-decreasing subsequences of the given array with at least two elements. You may return the answer in any order. Example 1: Input: nums = [4,6,7,7] Output: [[4,6],[4,6,7],[4,6,7,7],[4,7],[4,7,7],[6,7],[6,7,7],[7,7]] Example 2: Input: nums = [4,4,3,2,1] Output: [[4,4]] Constraints: 1 <= nums.length <= 15 -100 <= nums[i] <= 100
Python DFS
293
increasing-subsequences
0.521
hX_
Medium
8,566
491
construct the rectangle
class Solution: def constructRectangle(self, area: int) -> List[int]: for i in range(int(area**0.5),0,-1): if area % i == 0: return [area//i,i]
https://leetcode.com/problems/construct-the-rectangle/discuss/1990625/Python-Easy-Solution-or-Faster-Than-92-Submits
3
A web developer needs to know how to design a web page's size. So, given a specific rectangular web page’s area, your job by now is to design a rectangular web page, whose length L and width W satisfy the following requirements: The area of the rectangular web page you designed must equal to the given target area. The width W should not be larger than the length L, which means L >= W. The difference between length L and width W should be as small as possible. Return an array [L, W] where L and W are the length and width of the web page you designed in sequence. Example 1: Input: area = 4 Output: [2,2] Explanation: The target area is 4, and all the possible ways to construct it are [1,4], [2,2], [4,1]. But according to requirement 2, [1,4] is illegal; according to requirement 3, [4,1] is not optimal compared to [2,2]. So the length L is 2, and the width W is 2. Example 2: Input: area = 37 Output: [37,1] Example 3: Input: area = 122122 Output: [427,286] Constraints: 1 <= area <= 107
[ Python ] Easy Solution | Faster Than 92% Submits
300
construct-the-rectangle
0.538
crazypuppy
Easy
8,583
492
reverse pairs
class Solution: def reversePairs(self, nums: List[int]) -> int: ans = 0 seen = [] for x in nums: k = bisect_right(seen, 2*x) ans += len(seen) - k insort(seen, x) return ans
https://leetcode.com/problems/reverse-pairs/discuss/1205560/Python3-summarizing-4-solutions
5
Given an integer array nums, return the number of reverse pairs in the array. A reverse pair is a pair (i, j) where: 0 <= i < j < nums.length and nums[i] > 2 * nums[j]. Example 1: Input: nums = [1,3,2,3,1] Output: 2 Explanation: The reverse pairs are: (1, 4) --> nums[1] = 3, nums[4] = 1, 3 > 2 * 1 (3, 4) --> nums[3] = 3, nums[4] = 1, 3 > 2 * 1 Example 2: Input: nums = [2,4,3,5,1] Output: 3 Explanation: The reverse pairs are: (1, 4) --> nums[1] = 4, nums[4] = 1, 4 > 2 * 1 (2, 4) --> nums[2] = 3, nums[4] = 1, 3 > 2 * 1 (3, 4) --> nums[3] = 5, nums[4] = 1, 5 > 2 * 1 Constraints: 1 <= nums.length <= 5 * 104 -231 <= nums[i] <= 231 - 1
[Python3] summarizing 4 solutions
223
reverse-pairs
0.309
ye15
Hard
8,600
493
target sum
class Solution: def findTargetSumWays(self, nums: List[int], target: int) -> int: dic = defaultdict(int) def dfs(index=0, total=0): key = (index, total) if key not in dic: if index == len(nums): return 1 if total == target else 0 else: dic[key] = dfs(index+1, total + nums[index]) + dfs(index+1, total - nums[index]) return dic[key] return dfs()
https://leetcode.com/problems/target-sum/discuss/1198338/Python-recursive-solution-with-memoization-(DFS)
22
You are given an integer array nums and an integer target. You want to build an expression out of nums by adding one of the symbols '+' and '-' before each integer in nums and then concatenate all the integers. For example, if nums = [2, 1], you can add a '+' before 2 and a '-' before 1 and concatenate them to build the expression "+2-1". Return the number of different expressions that you can build, which evaluates to target. Example 1: Input: nums = [1,1,1,1,1], target = 3 Output: 5 Explanation: There are 5 ways to assign symbols to make the sum of nums be target 3. -1 + 1 + 1 + 1 + 1 = 3 +1 - 1 + 1 + 1 + 1 = 3 +1 + 1 - 1 + 1 + 1 = 3 +1 + 1 + 1 - 1 + 1 = 3 +1 + 1 + 1 + 1 - 1 = 3 Example 2: Input: nums = [1], target = 1 Output: 1 Constraints: 1 <= nums.length <= 20 0 <= nums[i] <= 1000 0 <= sum(nums[i]) <= 1000 -1000 <= target <= 1000
Python, recursive solution with memoization (DFS)
1,500
target-sum
0.456
swissified
Medium
8,608
494
teemo attacking
class Solution(object): def findPoisonedDuration(self, timeSeries, duration): repeat = 0 for i in range(len(timeSeries)-1): diff = timeSeries[i+1] - timeSeries[i] if diff < duration: repeat += duration - diff return len(timeSeries)*duration - repeat
https://leetcode.com/problems/teemo-attacking/discuss/1602614/Python-6-lines-O(n)-concise-solution
8
Our hero Teemo is attacking an enemy Ashe with poison attacks! When Teemo attacks Ashe, Ashe gets poisoned for a exactly duration seconds. More formally, an attack at second t will mean Ashe is poisoned during the inclusive time interval [t, t + duration - 1]. If Teemo attacks again before the poison effect ends, the timer for it is reset, and the poison effect will end duration seconds after the new attack. You are given a non-decreasing integer array timeSeries, where timeSeries[i] denotes that Teemo attacks Ashe at second timeSeries[i], and an integer duration. Return the total number of seconds that Ashe is poisoned. Example 1: Input: timeSeries = [1,4], duration = 2 Output: 4 Explanation: Teemo's attacks on Ashe go as follows: - At second 1, Teemo attacks, and Ashe is poisoned for seconds 1 and 2. - At second 4, Teemo attacks, and Ashe is poisoned for seconds 4 and 5. Ashe is poisoned for seconds 1, 2, 4, and 5, which is 4 seconds in total. Example 2: Input: timeSeries = [1,2], duration = 2 Output: 3 Explanation: Teemo's attacks on Ashe go as follows: - At second 1, Teemo attacks, and Ashe is poisoned for seconds 1 and 2. - At second 2 however, Teemo attacks again and resets the poison timer. Ashe is poisoned for seconds 2 and 3. Ashe is poisoned for seconds 1, 2, and 3, which is 3 seconds in total. Constraints: 1 <= timeSeries.length <= 104 0 <= timeSeries[i], duration <= 107 timeSeries is sorted in non-decreasing order.
Python 6 lines O(n) concise solution
330
teemo-attacking
0.57
caitlinttl
Easy
8,652
495
next greater element i
class Solution: def nextGreaterElement(self, nums1: List[int], nums2: List[int]) -> List[int]: # a stack with monotonic decreasing monotonic_stack = [] # dictionary: # key: number # value: next greater number of key dict_of_greater_number = {} # ---------------------------------------------- # launch linear scan to build dict_of_greater_number for cur_number in nums2: # maintain a monotonic decreasing stack while monotonic_stack and cur_number > monotonic_stack[-1]: pop_out_number = monotonic_stack.pop() # next greater number of pop_out_number is cur_number dict_of_greater_number[pop_out_number] = cur_number monotonic_stack.append(cur_number) # ---------------------------------------------- # solution output next_greater_element = [] # get next greater element by dictionary for x in nums1: if x in dict_of_greater_number: next_greater_element.append( dict_of_greater_number[x] ) else: next_greater_element.append(-1) return next_greater_element
https://leetcode.com/problems/next-greater-element-i/discuss/640416/Python-sol-by-monotonic-stack-and-dict-w-Comment
14
The next greater element of some element x in an array is the first greater element that is to the right of x in the same array. You are given two distinct 0-indexed integer arrays nums1 and nums2, where nums1 is a subset of nums2. For each 0 <= i < nums1.length, find the index j such that nums1[i] == nums2[j] and determine the next greater element of nums2[j] in nums2. If there is no next greater element, then the answer for this query is -1. Return an array ans of length nums1.length such that ans[i] is the next greater element as described above. Example 1: Input: nums1 = [4,1,2], nums2 = [1,3,4,2] Output: [-1,3,-1] Explanation: The next greater element for each value of nums1 is as follows: - 4 is underlined in nums2 = [1,3,4,2]. There is no next greater element, so the answer is -1. - 1 is underlined in nums2 = [1,3,4,2]. The next greater element is 3. - 2 is underlined in nums2 = [1,3,4,2]. There is no next greater element, so the answer is -1. Example 2: Input: nums1 = [2,4], nums2 = [1,2,3,4] Output: [3,-1] Explanation: The next greater element for each value of nums1 is as follows: - 2 is underlined in nums2 = [1,2,3,4]. The next greater element is 3. - 4 is underlined in nums2 = [1,2,3,4]. There is no next greater element, so the answer is -1. Constraints: 1 <= nums1.length <= nums2.length <= 1000 0 <= nums1[i], nums2[i] <= 104 All integers in nums1 and nums2 are unique. All the integers of nums1 also appear in nums2. Follow up: Could you find an O(nums1.length + nums2.length) solution?
Python sol by monotonic stack and dict [w/ Comment ]
968
next-greater-element-i
0.714
brianchiang_tw
Easy
8,673
496
random point in non overlapping rectangles
class Solution: def __init__(self, rects: List[List[int]]): self.rects = rects self.search_space = [] for i, rect in enumerate(rects): a, b, c, d = rect self.search_space.append((d - b + 1) * (c - a + 1)) if i != 0: self.search_space[i] += self.search_space[i - 1] def pick(self) -> List[int]: randval = random.randint(0, self.search_space[-1] - 1) low = 0 high = len(self.search_space) - 1 while low < high: midpt = low + (high - low) // 2 if self.search_space[midpt] <= randval: low = midpt + 1 else: high = midpt rect = self.rects[low] rect_range = randval if low > 0: rect_range -= self.search_space[low - 1] a, b, c, d = rect return [(rect_range % (c - a + 1)) + a, (rect_range // (c - a + 1)) + b]
https://leetcode.com/problems/random-point-in-non-overlapping-rectangles/discuss/1453111/Python-Binary-Search
1
You are given an array of non-overlapping axis-aligned rectangles rects where rects[i] = [ai, bi, xi, yi] indicates that (ai, bi) is the bottom-left corner point of the ith rectangle and (xi, yi) is the top-right corner point of the ith rectangle. Design an algorithm to pick a random integer point inside the space covered by one of the given rectangles. A point on the perimeter of a rectangle is included in the space covered by the rectangle. Any integer point inside the space covered by one of the given rectangles should be equally likely to be returned. Note that an integer point is a point that has integer coordinates. Implement the Solution class: Solution(int[][] rects) Initializes the object with the given rectangles rects. int[] pick() Returns a random integer point [u, v] inside the space covered by one of the given rectangles. Example 1: Input ["Solution", "pick", "pick", "pick", "pick", "pick"] [[[[-2, -2, 1, 1], [2, 2, 4, 6]]], [], [], [], [], []] Output [null, [1, -2], [1, -1], [-1, -2], [-2, -2], [0, 0]] Explanation Solution solution = new Solution([[-2, -2, 1, 1], [2, 2, 4, 6]]); solution.pick(); // return [1, -2] solution.pick(); // return [1, -1] solution.pick(); // return [-1, -2] solution.pick(); // return [-2, -2] solution.pick(); // return [0, 0] Constraints: 1 <= rects.length <= 100 rects[i].length == 4 -109 <= ai < xi <= 109 -109 <= bi < yi <= 109 xi - ai <= 2000 yi - bi <= 2000 All the rectangles do not overlap. At most 104 calls will be made to pick.
Python Binary Search
155
random-point-in-non-overlapping-rectangles
0.393
ypatel38
Medium
8,722
497
diagonal traverse
class Solution: def findDiagonalOrder(self, matrix: List[List[int]]) -> List[int]: res = [] if not matrix: return res # group values in matrix by the sum of their indices in a map map = {} for i in range(len(matrix) + len(matrix[0]) - 1): map[i] = [] # populate the map for i, row in enumerate(matrix): for j, val in enumerate(row): map[i + j].append(val) # iterate through map and reverse values where key is divisible by two for k, v in map.items(): if k % 2 == 0: map[k] = v[::-1] # populate output for v in map.values(): for val in v: res.append(val) return res
https://leetcode.com/problems/diagonal-traverse/discuss/272114/Simple-Python-Solution-(with-comments)
5
Given an m x n matrix mat, return an array of all the elements of the array in a diagonal order. Example 1: Input: mat = [[1,2,3],[4,5,6],[7,8,9]] Output: [1,2,4,7,5,3,6,8,9] Example 2: Input: mat = [[1,2],[3,4]] Output: [1,2,3,4] Constraints: m == mat.length n == mat[i].length 1 <= m, n <= 104 1 <= m * n <= 104 -105 <= mat[i][j] <= 105
Simple Python Solution (with comments)
612
diagonal-traverse
0.581
AnthonyChao
Medium
8,726
498
keyboard row
class Solution: def findWords(self, wds: List[str]) -> List[str]: st = {'q': 1, 'w': 1, 'e': 1, 'r': 1, 't': 1, 'y': 1, 'u': 1, 'i': 1, 'o': 1, 'p': 1, 'a': 2, 's': 2, 'd': 2, 'f': 2, 'g': 2, 'h': 2, 'j': 2, 'k': 2, 'l': 2, 'z': 3, 'x': 3, 'c': 3, 'v': 3, 'b': 3, 'n': 3, 'm': 3} ret = [] for wd in wds: val = 0 for i in range(len(wd)): if i == 0: val = st.get(wd[i].lower()) else: if val != st.get(wd[i].lower()): val = -1 break if val != -1: ret.append(wd) return ret
https://leetcode.com/problems/keyboard-row/discuss/1525751/Easy-Python-Solution-or-Faster-than-97-(24-ms)
5
Given an array of strings words, return the words that can be typed using letters of the alphabet on only one row of American keyboard like the image below. In the American keyboard: the first row consists of the characters "qwertyuiop", the second row consists of the characters "asdfghjkl", and the third row consists of the characters "zxcvbnm". Example 1: Input: words = ["Hello","Alaska","Dad","Peace"] Output: ["Alaska","Dad"] Example 2: Input: words = ["omk"] Output: [] Example 3: Input: words = ["adsdf","sfd"] Output: ["adsdf","sfd"] Constraints: 1 <= words.length <= 20 1 <= words[i].length <= 100 words[i] consists of English letters (both lowercase and uppercase).
Easy Python Solution | Faster than 97% (24 ms)
462
keyboard-row
0.692
the_sky_high
Easy
8,764
500
find mode in binary search tree
class Solution: def findMode(self, root: Optional[TreeNode]) -> List[int]: def traverse(root: TreeNode) -> None: if not root: return nonlocal maxcount, count, prevval, modes traverse(root.left) if root.val == prevval: count += 1 else: count = 1 if count > maxcount: maxcount = count modes = [root.val] elif count == maxcount: modes.append(root.val) prevval = root.val traverse(root.right) modes = [] maxcount = 0 count = 0 prevval = root.val traverse(root) return modes
https://leetcode.com/problems/find-mode-in-binary-search-tree/discuss/1722526/Python3-Inorder-traversal-beats-99
2
Given the root of a binary search tree (BST) with duplicates, return all the mode(s) (i.e., the most frequently occurred element) in it. If the tree has more than one mode, return them in any order. Assume a BST is defined as follows: The left subtree of a node contains only nodes with keys less than or equal to the node's key. The right subtree of a node contains only nodes with keys greater than or equal to the node's key. Both the left and right subtrees must also be binary search trees. Example 1: Input: root = [1,null,2,2] Output: [2] Example 2: Input: root = [0] Output: [0] Constraints: The number of nodes in the tree is in the range [1, 104]. -105 <= Node.val <= 105 Follow up: Could you do that without using any extra space? (Assume that the implicit stack space incurred due to recursion does not count).
[Python3] Inorder traversal; beats 99%
90
find-mode-in-binary-search-tree
0.487
cwkirby
Easy
8,812
501
ipo
class Solution: def findMaximizedCapital(self, k: int, w: int, profits: List[int], capital: List[int]) -> int: capital, profits = zip(*sorted(zip(capital, profits))) i = 0 pq = [] for _ in range(k): while i < len(capital) and capital[i] <= w: heappush(pq, -profits[i]) i += 1 if pq: w -= heappop(pq) return w
https://leetcode.com/problems/ipo/discuss/1492025/Python3-greedy
1
Suppose LeetCode will start its IPO soon. In order to sell a good price of its shares to Venture Capital, LeetCode would like to work on some projects to increase its capital before the IPO. Since it has limited resources, it can only finish at most k distinct projects before the IPO. Help LeetCode design the best way to maximize its total capital after finishing at most k distinct projects. You are given n projects where the ith project has a pure profit profits[i] and a minimum capital of capital[i] is needed to start it. Initially, you have w capital. When you finish a project, you will obtain its pure profit and the profit will be added to your total capital. Pick a list of at most k distinct projects from given projects to maximize your final capital, and return the final maximized capital. The answer is guaranteed to fit in a 32-bit signed integer. Example 1: Input: k = 2, w = 0, profits = [1,2,3], capital = [0,1,1] Output: 4 Explanation: Since your initial capital is 0, you can only start the project indexed 0. After finishing it you will obtain profit 1 and your capital becomes 1. With capital 1, you can either start the project indexed 1 or the project indexed 2. Since you can choose at most 2 projects, you need to finish the project indexed 2 to get the maximum capital. Therefore, output the final maximized capital, which is 0 + 1 + 3 = 4. Example 2: Input: k = 3, w = 0, profits = [1,2,3], capital = [0,1,2] Output: 6 Constraints: 1 <= k <= 105 0 <= w <= 109 n == profits.length n == capital.length 1 <= n <= 105 0 <= profits[i] <= 104 0 <= capital[i] <= 109
[Python3] greedy
144
ipo
0.45
ye15
Hard
8,832
502
next greater element ii
class Solution: def nextGreaterElements(self, nums: List[int]) -> List[int]: stack, res = [], [-1] * len(nums) # taking an empty stack for storing index, a list with the lenght same as of nums so that we wont add unnecessary elements. # [-1] * len(nums) = this will produce a list with len of nums and all elems will be -1. for i in list(range(len(nums))) * 2: # see explanation below. while stack and (nums[stack[-1]] < nums[i]): # stack is not empty and nums previous elem is less then current, i.e 1<2. res[stack.pop()] = nums[i] # then we`ll pop the index in stack and in the res on the same index will add the current num. stack.append(i) # if stack is empty then we`ll add the index of num in it for comparision to the next element in the provided list. return res # returing the next greater number for every element in nums.
https://leetcode.com/problems/next-greater-element-ii/discuss/2520585/Python-Stack-98.78-faster-or-Simplest-solution-with-explanation-or-Beg-to-Adv-or-Monotonic-Stack
3
Given a circular integer array nums (i.e., the next element of nums[nums.length - 1] is nums[0]), return the next greater number for every element in nums. The next greater number of a number x is the first greater number to its traversing-order next in the array, which means you could search circularly to find its next greater number. If it doesn't exist, return -1 for this number. Example 1: Input: nums = [1,2,1] Output: [2,-1,2] Explanation: The first 1's next greater number is 2; The number 2 can't find next greater number. The second 1's next greater number needs to search circularly, which is also 2. Example 2: Input: nums = [1,2,3,4,3] Output: [2,3,4,-1,4] Constraints: 1 <= nums.length <= 104 -109 <= nums[i] <= 109
Python Stack 98.78% faster | Simplest solution with explanation | Beg to Adv | Monotonic Stack
279
next-greater-element-ii
0.631
rlakshay14
Medium
8,836
503
base 7
class Solution: def convertToBase7(self, num: int) -> str: if not num: return "0" l=[] x=num if num<0: num=-num while num>0: r=num%7 l.append(str(r)) num//=7 return "".join(l[::-1]) if x>=0 else "-"+ "".join(l[::-1])
https://leetcode.com/problems/base-7/discuss/1014922/Simple-and-easy-faster-than-99.31
4
Given an integer num, return a string of its base 7 representation. Example 1: Input: num = 100 Output: "202" Example 2: Input: num = -7 Output: "-10" Constraints: -107 <= num <= 107
Simple and easy - faster than 99.31%
607
base-7
0.48
thisisakshat
Easy
8,882
504
relative ranks
class Solution: def findRelativeRanks(self, score: List[int]) -> List[str]: rankings = [] for i, val in enumerate(score): heappush(rankings, (-val, i)) ans = [''] * len(score) r = 1 rank = ["Gold Medal", "Silver Medal", "Bronze Medal"] while len(rankings) != 0: _, i = heappop(rankings) if r <= 3: ans[i] = rank[r-1] else: ans[i] = f'{r}' r += 1 return ans
https://leetcode.com/problems/relative-ranks/discuss/1705542/Python-Simple-Solution-using-Max-Heap
8
You are given an integer array score of size n, where score[i] is the score of the ith athlete in a competition. All the scores are guaranteed to be unique. The athletes are placed based on their scores, where the 1st place athlete has the highest score, the 2nd place athlete has the 2nd highest score, and so on. The placement of each athlete determines their rank: The 1st place athlete's rank is "Gold Medal". The 2nd place athlete's rank is "Silver Medal". The 3rd place athlete's rank is "Bronze Medal". For the 4th place to the nth place athlete, their rank is their placement number (i.e., the xth place athlete's rank is "x"). Return an array answer of size n where answer[i] is the rank of the ith athlete. Example 1: Input: score = [5,4,3,2,1] Output: ["Gold Medal","Silver Medal","Bronze Medal","4","5"] Explanation: The placements are [1st, 2nd, 3rd, 4th, 5th]. Example 2: Input: score = [10,3,8,9,4] Output: ["Gold Medal","5","Bronze Medal","Silver Medal","4"] Explanation: The placements are [1st, 5th, 3rd, 2nd, 4th]. Constraints: n == score.length 1 <= n <= 104 0 <= score[i] <= 106 All the values in score are unique.
[Python] Simple Solution using Max-Heap
573
relative-ranks
0.592
anCoderr
Easy
8,896
506
perfect number
class Solution: def checkPerfectNumber(self, num: int) -> bool: if num == 1: return False res = 1 for i in range(2,int(num**0.5)+1): if num%i == 0: res += i + num//i return res == num
https://leetcode.com/problems/perfect-number/discuss/1268856/Python3-simple-solution
10
A perfect number is a positive integer that is equal to the sum of its positive divisors, excluding the number itself. A divisor of an integer x is an integer that can divide x evenly. Given an integer n, return true if n is a perfect number, otherwise return false. Example 1: Input: num = 28 Output: true Explanation: 28 = 1 + 2 + 4 + 7 + 14 1, 2, 4, 7, and 14 are all divisors of 28. Example 2: Input: num = 7 Output: false Constraints: 1 <= num <= 108
Python3 simple solution
439
perfect-number
0.378
EklavyaJoshi
Easy
8,928
507
most frequent subtree sum
class Solution: def findFrequentTreeSum(self, root: TreeNode) -> List[int]: counts = collections.Counter() def dfs(node): if not node: return 0 result = node.val + dfs(node.left) + dfs(node.right) counts[result] += 1 return result dfs(root) # Try to return the most frequent elements # Return [] if we run into index errors try: freq = counts.most_common(1)[0][1] return [x[0] for x in counts.items() if x[1] == freq] except: return []
https://leetcode.com/problems/most-frequent-subtree-sum/discuss/1101640/A-Basic-Python
1
Given the root of a binary tree, return the most frequent subtree sum. If there is a tie, return all the values with the highest frequency in any order. The subtree sum of a node is defined as the sum of all the node values formed by the subtree rooted at that node (including the node itself). Example 1: Input: root = [5,2,-3] Output: [2,-3,4] Example 2: Input: root = [5,2,-5] Output: [2] Constraints: The number of nodes in the tree is in the range [1, 104]. -105 <= Node.val <= 105
A Basic Python
117
most-frequent-subtree-sum
0.644
dev-josh
Medium
8,945
508
fibonacci number
class Solution: def fib(self, N: int) -> int: a, b = 0, 1 for i in range(N): a, b = b, a + b return a - Python 3 - Junaid Mansuri
https://leetcode.com/problems/fibonacci-number/discuss/336501/Solution-in-Python-3-(beats-~100)-(three-lines)
41
The Fibonacci numbers, commonly denoted F(n) form a sequence, called the Fibonacci sequence, such that each number is the sum of the two preceding ones, starting from 0 and 1. That is, F(0) = 0, F(1) = 1 F(n) = F(n - 1) + F(n - 2), for n > 1. Given n, calculate F(n). Example 1: Input: n = 2 Output: 1 Explanation: F(2) = F(1) + F(0) = 1 + 0 = 1. Example 2: Input: n = 3 Output: 2 Explanation: F(3) = F(2) + F(1) = 1 + 1 = 2. Example 3: Input: n = 4 Output: 3 Explanation: F(4) = F(3) + F(2) = 2 + 1 = 3. Constraints: 0 <= n <= 30
Solution in Python 3 (beats ~100%) (three lines)
6,700
fibonacci-number
0.692
junaidmansuri
Easy
8,953
509
find bottom left tree value
class Solution: def findBottomLeftValue(self, root: Optional[TreeNode]) -> int: q=[[root]] nodes=[] while q: nodes = q.pop(0) t=[] for n in nodes: if n.left: t.append(n.left) if n.right: t.append(n.right) if t: q.append(t) return nodes[0].val # Please upvote if you understand the solution
https://leetcode.com/problems/find-bottom-left-tree-value/discuss/2680305/Pyhton3-BFS-Solution-oror-BGG
1
Given the root of a binary tree, return the leftmost value in the last row of the tree. Example 1: Input: root = [2,1,3] Output: 1 Example 2: Input: root = [1,2,3,4,null,5,6,null,null,7] Output: 7 Constraints: The number of nodes in the tree is in the range [1, 104]. -231 <= Node.val <= 231 - 1
Pyhton3 BFS Solution || BGG
151
find-bottom-left-tree-value
0.665
hoo__mann
Medium
9,027
513
freedom trail
class Solution: def findRotateSteps(self, ring: str, key: str) -> int: locs = {} for i, ch in enumerate(ring): locs.setdefault(ch, []).append(i) @cache def fn(i, j): """Return turns to finish key[j:] startin from ith position on ring.""" if j == len(key): return 0 loc = locs[key[j]] k = bisect_left(loc, i) % len(loc) ans = min(abs(i-loc[k]), len(ring) - abs(i-loc[k])) + fn(loc[k], j+1) k = (k-1) % len(loc) ans = min(ans, min(abs(i-loc[k]), len(ring) - abs(i-loc[k])) + fn(loc[k], j+1)) return ans return fn(0, 0) + len(key)
https://leetcode.com/problems/freedom-trail/discuss/1367426/Python3-top-down-dp
2
In the video game Fallout 4, the quest "Road to Freedom" requires players to reach a metal dial called the "Freedom Trail Ring" and use the dial to spell a specific keyword to open the door. Given a string ring that represents the code engraved on the outer ring and another string key that represents the keyword that needs to be spelled, return the minimum number of steps to spell all the characters in the keyword. Initially, the first character of the ring is aligned at the "12:00" direction. You should spell all the characters in key one by one by rotating ring clockwise or anticlockwise to make each character of the string key aligned at the "12:00" direction and then by pressing the center button. At the stage of rotating the ring to spell the key character key[i]: You can rotate the ring clockwise or anticlockwise by one place, which counts as one step. The final purpose of the rotation is to align one of ring's characters at the "12:00" direction, where this character must equal key[i]. If the character key[i] has been aligned at the "12:00" direction, press the center button to spell, which also counts as one step. After the pressing, you could begin to spell the next character in the key (next stage). Otherwise, you have finished all the spelling. Example 1: Input: ring = "godding", key = "gd" Output: 4 Explanation: For the first key character 'g', since it is already in place, we just need 1 step to spell this character. For the second key character 'd', we need to rotate the ring "godding" anticlockwise by two steps to make it become "ddinggo". Also, we need 1 more step for spelling. So the final output is 4. Example 2: Input: ring = "godding", key = "godding" Output: 13 Constraints: 1 <= ring.length, key.length <= 100 ring and key consist of only lower case English letters. It is guaranteed that key could always be spelled by rotating ring.
[Python3] top-down dp
165
freedom-trail
0.467
ye15
Hard
9,051
514
find largest value in each tree row
class Solution: def largestValues(self, root: Optional[TreeNode]) -> List[int]: res = [] def helper(root, depth): if root is None: return if depth == len(res): res.append(root.val) else: res[depth] = max(res[depth], root.val) helper(root.left, depth + 1) helper(root.right, depth + 1) helper(root, 0) return res
https://leetcode.com/problems/find-largest-value-in-each-tree-row/discuss/1620422/Python-3-easy-dfs-recursive-solution-faster-than-94
1
Given the root of a binary tree, return an array of the largest value in each row of the tree (0-indexed). Example 1: Input: root = [1,3,2,5,3,null,9] Output: [1,3,9] Example 2: Input: root = [1,2,3] Output: [1,3] Constraints: The number of nodes in the tree will be in the range [0, 104]. -231 <= Node.val <= 231 - 1
Python 3, easy dfs recursive solution, faster than 94%
109
find-largest-value-in-each-tree-row
0.646
dereky4
Medium
9,053
515