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
shortest palindrome
class Solution: def shortestPalindrome(self, s: str) -> str: end = 0 # if the string itself is a palindrome return it if(s == s[::-1]): return s # Otherwise find the end index of the longest palindrome that starts # from the first character of the string for i in range(len(s)+1): if(s[:i]==s[:i][::-1]): end=i-1 # return the string with the remaining characters other than # the palindrome reversed and added at the beginning return (s[end+1:][::-1])+s
https://leetcode.com/problems/shortest-palindrome/discuss/2157861/No-DP-No-DS-Intuitive-with-comments-oror-Python
2
You are given a string s. You can convert s to a palindrome by adding characters in front of it. Return the shortest palindrome you can find by performing this transformation. Example 1: Input: s = "aacecaaa" Output: "aaacecaaa" Example 2: Input: s = "abcd" Output: "dcbabcd" Constraints: 0 <= s.length <= 5 * 104 s consists of lowercase English letters only.
No DP; No DS; Intuitive with comments || Python
124
shortest-palindrome
0.322
a-myth
Hard
3,694
214
kth largest element in an array
class Solution: def findKthLargest(self, nums: List[int], k: int) -> int: n = len(nums) def partition(l, r, pivot): pivot_elem=nums[pivot] nums[r],nums[pivot]=nums[pivot],nums[r] index=l for i in range(l, r): if nums[i]<pivot_elem: nums[i],nums[index]=nums[index],nums[i] index+=1 nums[index],nums[r]=nums[r],nums[index] return index def quick_select(l,r,kth_index): if l==r: return nums[l] pivot_index=partition(l,r,l) if pivot_index==kth_index: return nums[pivot_index] if kth_index>pivot_index: return quick_select(pivot_index+1, r, kth_index) else: return quick_select(l,pivot_index-1, kth_index) return quick_select(0, n - 1, n - k)
https://leetcode.com/problems/kth-largest-element-in-an-array/discuss/2180509/Python-Easy-O(logn)-Space-approach-or-One-liner
24
Given an integer array nums and an integer k, return the kth largest element in the array. Note that it is the kth largest element in the sorted order, not the kth distinct element. Can you solve it without sorting? Example 1: Input: nums = [3,2,1,5,6,4], k = 2 Output: 5 Example 2: Input: nums = [3,2,3,1,2,4,5,5,6], k = 4 Output: 4 Constraints: 1 <= k <= nums.length <= 105 -104 <= nums[i] <= 104
Python Easy O(logn) Space approach | One liner
3,300
kth-largest-element-in-an-array
0.658
constantine786
Medium
3,711
215
combination sum iii
class Solution: def combinationSum3(self, k: int, n: int) -> List[List[int]]: current_combination, combinations = [], [] integer, combination_sum = 1, 0 queue = [(integer, current_combination, combination_sum)] while queue: integer, current_combination, combination_sum = queue.pop() if combination_sum == n and len(current_combination) == k: combinations.append(current_combination) else: for i in range(integer, 10): if combination_sum + i > n: break queue.append((i+1, current_combination + [i], combination_sum + i)) return combinations
https://leetcode.com/problems/combination-sum-iii/discuss/1312030/Elegant-Python-Iterative-or-Recursive
5
Find all valid combinations of k numbers that sum up to n such that the following conditions are true: Only numbers 1 through 9 are used. Each number is used at most once. Return a list of all possible valid combinations. The list must not contain the same combination twice, and the combinations may be returned in any order. Example 1: Input: k = 3, n = 7 Output: [[1,2,4]] Explanation: 1 + 2 + 4 = 7 There are no other valid combinations. Example 2: Input: k = 3, n = 9 Output: [[1,2,6],[1,3,5],[2,3,4]] Explanation: 1 + 2 + 6 = 9 1 + 3 + 5 = 9 2 + 3 + 4 = 9 There are no other valid combinations. Example 3: Input: k = 4, n = 1 Output: [] Explanation: There are no valid combinations. Using 4 different numbers in the range [1,9], the smallest sum we can get is 1+2+3+4 = 10 and since 10 > 1, there are no valid combination. Constraints: 2 <= k <= 9 1 <= n <= 60
Elegant Python Iterative | Recursive
175
combination-sum-iii
0.672
soma28
Medium
3,761
216
contains duplicate
class Solution: def containsDuplicate(self, nums: List[int]) -> bool: return len(set(nums)) != len(nums)
https://leetcode.com/problems/contains-duplicate/discuss/1496268/Python-98-speed-faster
11
Given an integer array nums, return true if any value appears at least twice in the array, and return false if every element is distinct. Example 1: Input: nums = [1,2,3,1] Output: true Example 2: Input: nums = [1,2,3,4] Output: false Example 3: Input: nums = [1,1,1,3,3,4,3,2,4,2] Output: true Constraints: 1 <= nums.length <= 105 -109 <= nums[i] <= 109
Python // 98% speed faster
1,900
contains-duplicate
0.613
fabioo29
Easy
3,811
217
the skyline problem
class Solution: def getSkyline(self, buildings: List[List[int]]) -> List[List[int]]: # for the same x, (x, -H) should be in front of (x, 0) # For Example 2, we should process (2, -3) then (2, 0), as there's no height change x_height_right_tuples = sorted([(L, -H, R) for L, R, H in buildings] + [(R, 0, "doesn't matter") for _, R, _ in buildings]) # (0, float('inf')) is always in max_heap, so max_heap[0] is always valid result, max_heap = [[0, 0]], [(0, float('inf'))] for x, negative_height, R in x_height_right_tuples: while x >= max_heap[0][1]: # reduce max height up to date, i.e. only consider max height in the right side of line x heapq.heappop(max_heap) if negative_height: # Consider each height, as it may be the potential max height heapq.heappush(max_heap, (negative_height, R)) curr_max_height = -max_heap[0][0] if result[-1][1] != curr_max_height: result.append([x, curr_max_height]) return result[1:]
https://leetcode.com/problems/the-skyline-problem/discuss/2640697/Python-oror-Easily-Understood-oror-Faster-oror-with-maximum-heap-explained
12
A city's skyline is the outer contour of the silhouette formed by all the buildings in that city when viewed from a distance. Given the locations and heights of all the buildings, return the skyline formed by these buildings collectively. The geometric information of each building is given in the array buildings where buildings[i] = [lefti, righti, heighti]: lefti is the x coordinate of the left edge of the ith building. righti is the x coordinate of the right edge of the ith building. heighti is the height of the ith building. You may assume all buildings are perfect rectangles grounded on an absolutely flat surface at height 0. The skyline should be represented as a list of "key points" sorted by their x-coordinate in the form [[x1,y1],[x2,y2],...]. Each key point is the left endpoint of some horizontal segment in the skyline except the last point in the list, which always has a y-coordinate 0 and is used to mark the skyline's termination where the rightmost building ends. Any ground between the leftmost and rightmost buildings should be part of the skyline's contour. Note: There must be no consecutive horizontal lines of equal height in the output skyline. For instance, [...,[2 3],[4 5],[7 5],[11 5],[12 7],...] is not acceptable; the three lines of height 5 should be merged into one in the final output as such: [...,[2 3],[4 5],[12 7],...] Example 1: Input: buildings = [[2,9,10],[3,7,15],[5,12,12],[15,20,10],[19,24,8]] Output: [[2,10],[3,15],[7,12],[12,0],[15,10],[20,8],[24,0]] Explanation: Figure A shows the buildings of the input. Figure B shows the skyline formed by those buildings. The red points in figure B represent the key points in the output list. Example 2: Input: buildings = [[0,2,3],[2,5,3]] Output: [[0,3],[5,0]] Constraints: 1 <= buildings.length <= 104 0 <= lefti < righti <= 231 - 1 1 <= heighti <= 231 - 1 buildings is sorted by lefti in non-decreasing order.
🔥 Python || Easily Understood ✅ || Faster || with maximum heap explained
1,100
the-skyline-problem
0.416
rajukommula
Hard
3,856
218
contains duplicate ii
class Solution: def containsNearbyDuplicate(self, nums: List[int], k: int) -> bool: # Create hset for storing previous of k elements... hset = {} # Traverse for all elements of the given array in a for loop... for idx in range(len(nums)): # If duplicate element is present at distance less than equal to k, return true... if nums[idx] in hset and abs(idx - hset[nums[idx]]) <= k: return True hset[nums[idx]] = idx # If no duplicate element is found then return false... return False
https://leetcode.com/problems/contains-duplicate-ii/discuss/2463150/Very-Easy-oror-100-oror-Fully-Explained-oror-Java-C%2B%2B-Python-Javascript-Python3-(Using-HashSet)
45
Given an integer array nums and an integer k, return true if there are two distinct indices i and j in the array such that nums[i] == nums[j] and abs(i - j) <= k. Example 1: Input: nums = [1,2,3,1], k = 3 Output: true Example 2: Input: nums = [1,0,1,1], k = 1 Output: true Example 3: Input: nums = [1,2,3,1,2,3], k = 2 Output: false Constraints: 1 <= nums.length <= 105 -109 <= nums[i] <= 109 0 <= k <= 105
Very Easy || 100% || Fully Explained || Java, C++, Python, Javascript, Python3 (Using HashSet)
3,400
contains-duplicate-ii
0.423
PratikSen07
Easy
3,870
219
contains duplicate iii
class Solution: def containsDuplicate(self, nums: List[int]) -> bool: seen = set() for x in nums: if x in seen: return True seen.add(x) return False
https://leetcode.com/problems/contains-duplicate-iii/discuss/825267/Python3-summarizing-Contain-Duplicates-I-II-III
22
You are given an integer array nums and two integers indexDiff and valueDiff. Find a pair of indices (i, j) such that: i != j, abs(i - j) <= indexDiff. abs(nums[i] - nums[j]) <= valueDiff, and Return true if such pair exists or false otherwise. Example 1: Input: nums = [1,2,3,1], indexDiff = 3, valueDiff = 0 Output: true Explanation: We can choose (i, j) = (0, 3). We satisfy the three conditions: i != j --> 0 != 3 abs(i - j) <= indexDiff --> abs(0 - 3) <= 3 abs(nums[i] - nums[j]) <= valueDiff --> abs(1 - 1) <= 0 Example 2: Input: nums = [1,5,9,1,5,9], indexDiff = 2, valueDiff = 3 Output: false Explanation: After trying all the possible pairs (i, j), we cannot satisfy the three conditions, so we return false. Constraints: 2 <= nums.length <= 105 -109 <= nums[i] <= 109 1 <= indexDiff <= nums.length 0 <= valueDiff <= 109
[Python3] summarizing Contain Duplicates I, II, III
689
contains-duplicate-iii
0.22
ye15
Hard
3,921
220
maximal square
class Solution: def maximalSquare(self, matrix: List[List[str]]) -> int: result = 0 for i in range(len(matrix)): for j in range(len(matrix[0])): curr = 0 # current length of the square at (i, j) flag = True # indicates if there still exists a valid square while flag: for k in range(curr+1): # check outer border of elements for '1's. """ eg curr = 2, ie a valid 2x2 square exists 'O' is valid, check 'X': X X X X O O X O O """ if i < curr or j < curr or \ matrix[i-curr][j-k] == '0' or \ matrix[i-k][j-curr] == '0': flag = False break curr += flag if curr > result: # new maximum length of square obtained result = curr return result*result # area = length x length
https://leetcode.com/problems/maximal-square/discuss/1632285/Python-1D-Array-DP-Optimisation-Process-Explained
9
Given an m x n binary matrix filled with 0's and 1's, find the largest square containing only 1's and return its area. Example 1: Input: matrix = [["1","0","1","0","0"],["1","0","1","1","1"],["1","1","1","1","1"],["1","0","0","1","0"]] Output: 4 Example 2: Input: matrix = [["0","1"],["1","0"]] Output: 1 Example 3: Input: matrix = [["0"]] Output: 0 Constraints: m == matrix.length n == matrix[i].length 1 <= m, n <= 300 matrix[i][j] is '0' or '1'.
[Python] 1D-Array DP - Optimisation Process Explained
610
maximal-square
0.446
zayne-siew
Medium
3,932
221
count complete tree nodes
class Solution: def countNodes(self, root: TreeNode) -> int: if not root: return 0 return 1 + self.countNodes(root.left) + self.countNodes(root.right)
https://leetcode.com/problems/count-complete-tree-nodes/discuss/701577/PythonPython3-Count-Complete-Tree-Nodes
4
Given the root of a complete binary tree, return the number of the nodes in the tree. According to Wikipedia, every level, except possibly the last, is completely filled in a complete binary tree, and all nodes in the last level are as far left as possible. It can have between 1 and 2h nodes inclusive at the last level h. Design an algorithm that runs in less than O(n) time complexity. Example 1: Input: root = [1,2,3,4,5,6] Output: 6 Example 2: Input: root = [] Output: 0 Example 3: Input: root = [1] Output: 1 Constraints: The number of nodes in the tree is in the range [0, 5 * 104]. 0 <= Node.val <= 5 * 104 The tree is guaranteed to be complete.
[Python/Python3] Count Complete Tree Nodes
336
count-complete-tree-nodes
0.598
newborncoder
Medium
3,976
222
rectangle area
class Solution: def computeArea(self, ax1: int, ay1: int, ax2: int, ay2: int, bx1: int, by1: int, bx2: int, by2: int) -> int: coxl=max(ax1,bx1) coxr=min(ax2,bx2) coyl=max(ay1,by1) coyr=min(ay2,by2) dx=coxr-coxl dy=coyr-coyl comm=0 if dx>0 and dy>0: comm=dx*dy a=abs(ax2-ax1)*abs(ay2-ay1) b=abs(bx2-bx1)*abs(by2-by1) area=a+b-comm return area
https://leetcode.com/problems/rectangle-area/discuss/2822409/Fastest-python-solution
9
Given the coordinates of two rectilinear rectangles in a 2D plane, return the total area covered by the two rectangles. The first rectangle is defined by its bottom-left corner (ax1, ay1) and its top-right corner (ax2, ay2). The second rectangle is defined by its bottom-left corner (bx1, by1) and its top-right corner (bx2, by2). Example 1: Input: ax1 = -3, ay1 = 0, ax2 = 3, ay2 = 4, bx1 = 0, by1 = -1, bx2 = 9, by2 = 2 Output: 45 Example 2: Input: ax1 = -2, ay1 = -2, ax2 = 2, ay2 = 2, bx1 = -2, by1 = -2, bx2 = 2, by2 = 2 Output: 16 Constraints: -104 <= ax1 <= ax2 <= 104 -104 <= ay1 <= ay2 <= 104 -104 <= bx1 <= bx2 <= 104 -104 <= by1 <= by2 <= 104
Fastest python solution
569
rectangle-area
0.449
shubham_1307
Medium
4,004
223
basic calculator
class Solution: def calculate(self, s: str) -> int: output, curr, sign, stack = 0, 0, 1, [] for c in s: if c.isdigit(): curr = (curr * 10) + int(c) elif c in '+-': output += curr * sign curr = 0 if c == '+': sign = 1 else: sign = -1 elif c == '(': stack.append(output) stack.append(sign) sign = 1 output = 0 elif c == ')': output += curr * sign output *= stack.pop() #sign output += stack.pop() #last output curr = 0 return output + (curr * sign)
https://leetcode.com/problems/basic-calculator/discuss/2832718/Python-(Faster-than-98)-or-O(N)-stack-solution
2
Given a string s representing a valid expression, implement a basic calculator to evaluate it, and return the result of the evaluation. Note: You are not allowed to use any built-in function which evaluates strings as mathematical expressions, such as eval(). Example 1: Input: s = "1 + 1" Output: 2 Example 2: Input: s = " 2-1 + 2 " Output: 3 Example 3: Input: s = "(1+(4+5+2)-3)+(6+8)" Output: 23 Constraints: 1 <= s.length <= 3 * 105 s consists of digits, '+', '-', '(', ')', and ' '. s represents a valid expression. '+' is not used as a unary operation (i.e., "+1" and "+(2 + 3)" is invalid). '-' could be used as a unary operation (i.e., "-1" and "-(2 + 3)" is valid). There will be no two consecutive operators in the input. Every number and running calculation will fit in a signed 32-bit integer.
Python (Faster than 98%) | O(N) stack solution
81
basic-calculator
0.423
KevinJM17
Hard
4,054
224
invert binary tree
class Solution(object): def invertTree(self, root): # Base case... if root == None: return root # swapping process... root.left, root.right = root.right, root.left # Call the function recursively for the left subtree... self.invertTree(root.left) # Call the function recursively for the right subtree... self.invertTree(root.right) return root # Return the root...
https://leetcode.com/problems/invert-binary-tree/discuss/2463600/Easy-oror-100-oror-Fully-Explained-oror-Java-C%2B%2B-Python-JS-C-Python3-oror-Recursive-and-Iterative
54
Given the root of a binary tree, invert the tree, and return its root. Example 1: Input: root = [4,2,7,1,3,6,9] Output: [4,7,2,9,6,3,1] Example 2: Input: root = [2,1,3] Output: [2,3,1] Example 3: Input: root = [] Output: [] Constraints: The number of nodes in the tree is in the range [0, 100]. -100 <= Node.val <= 100
Easy || 100% || Fully Explained || Java, C++, Python, JS, C, Python3 || Recursive & Iterative
3,300
invert-binary-tree
0.734
PratikSen07
Easy
4,091
226
basic calculator ii
class Solution: def calculate(self, s: str) -> int: curr_res = 0 res = 0 num = 0 op = "+" # keep the last operator we have seen # append a "+" sign at the end because we can catch the very last item for ch in s + "+": if ch.isdigit(): num = 10 * num + int(ch) # if we have a symbol, we would start to calculate the previous part. # note that we have to catch the last chracter since there will no sign afterwards to trigger calculation if ch in ("+", "-", "*", "/"): if op == "+": curr_res += num elif op == "-": curr_res -= num elif op == "*": curr_res *= num elif op == "/": # in python if there is a negative number, we should alway use int() instead of // curr_res = int(curr_res / num) # if the chracter is "+" or "-", we do not need to worry about # the priority so that we can add the curr_res to the eventual res if ch in ("+", "-"): res += curr_res curr_res = 0 op = ch num = 0 return res
https://leetcode.com/problems/basic-calculator-ii/discuss/1209116/python-without-any-stack-and-beat-99
14
Given a string s which represents an expression, evaluate this expression and return its value. The integer division should truncate toward zero. You may assume that the given expression is always valid. All intermediate results will be in the range of [-231, 231 - 1]. Note: You are not allowed to use any built-in function which evaluates strings as mathematical expressions, such as eval(). Example 1: Input: s = "3+2*2" Output: 7 Example 2: Input: s = " 3/2 " Output: 1 Example 3: Input: s = " 3+5 / 2 " Output: 5 Constraints: 1 <= s.length <= 3 * 105 s consists of integers and operators ('+', '-', '*', '/') separated by some number of spaces. s represents a valid expression. All the integers in the expression are non-negative integers in the range [0, 231 - 1]. The answer is guaranteed to fit in a 32-bit integer.
python - without any stack and beat 99%
1,300
basic-calculator-ii
0.423
ZAbird
Medium
4,123
227
summary ranges
class Solution: def summaryRanges(self, nums: List[int]) -> List[str]: start = 0 end = 0 result = [] while start < len(nums) and end<len(nums): if end+1 < len(nums) and nums[end]+1 == nums[end+1]: end=end+1 else: if start == end: result.append(str(nums[start])) start = start + 1 end = end + 1 else: result.append(str(nums[start])+'->'+str(nums[end])) start = end + 1 end = end + 1 return result
https://leetcode.com/problems/summary-ranges/discuss/1805476/Python-Simple-Python-Solution-Using-Iterative-Approach-oror-O(n)
28
You are given a sorted unique integer array nums. A range [a,b] is the set of all integers from a to b (inclusive). Return the smallest sorted list of ranges that cover all the numbers in the array exactly. That is, each element of nums is covered by exactly one of the ranges, and there is no integer x such that x is in one of the ranges but not in nums. Each range [a,b] in the list should be output as: "a->b" if a != b "a" if a == b Example 1: Input: nums = [0,1,2,4,5,7] Output: ["0->2","4->5","7"] Explanation: The ranges are: [0,2] --> "0->2" [4,5] --> "4->5" [7,7] --> "7" Example 2: Input: nums = [0,2,3,4,6,8,9] Output: ["0","2->4","6","8->9"] Explanation: The ranges are: [0,0] --> "0" [2,4] --> "2->4" [6,6] --> "6" [8,9] --> "8->9" Constraints: 0 <= nums.length <= 20 -231 <= nums[i] <= 231 - 1 All the values of nums are unique. nums is sorted in ascending order.
[ Python ] ✔✔ Simple Python Solution Using Iterative Approach || O(n) 🔥✌
2,300
summary-ranges
0.469
ASHOK_KUMAR_MEGHVANSHI
Easy
4,149
228
majority element ii
class Solution: def majorityElement(self, nums: List[int]) -> List[int]: return [x for x in set(nums) if nums.count(x) > len(nums)/3]
https://leetcode.com/problems/majority-element-ii/discuss/1483430/Python-95-faster-in-speed
3
Given an integer array of size n, find all elements that appear more than ⌊ n/3 ⌋ times. Example 1: Input: nums = [3,2,3] Output: [3] Example 2: Input: nums = [1] Output: [1] Example 3: Input: nums = [1,2] Output: [1,2] Constraints: 1 <= nums.length <= 5 * 104 -109 <= nums[i] <= 109 Follow up: Could you solve the problem in linear time and in O(1) space?
Python // 95% faster in speed
394
majority-element-ii
0.442
fabioo29
Medium
4,197
229
kth smallest element in a bst
class Solution: import heapq def kthSmallest(self, root: Optional[TreeNode], k: int) -> int: heap = [] def inorder(r): if r: inorder(r.left) heapq.heappush(heap,-(r.val)) if len(heap) > k: heapq.heappop(heap) inorder(r.right) inorder(root) return -heapq.heappop(heap)
https://leetcode.com/problems/kth-smallest-element-in-a-bst/discuss/1960632/Inorder-%2B-Heap-In-Python
2
Given the root of a binary search tree, and an integer k, return the kth smallest value (1-indexed) of all the values of the nodes in the tree. Example 1: Input: root = [3,1,4,null,2], k = 1 Output: 1 Example 2: Input: root = [5,3,6,2,4,null,null,1], k = 3 Output: 3 Constraints: The number of nodes in the tree is n. 1 <= k <= n <= 104 0 <= Node.val <= 104 Follow up: If the BST is modified often (i.e., we can do insert and delete operations) and you need to find the kth smallest frequently, how would you optimize?
Inorder + Heap In Python
83
kth-smallest-element-in-a-bst
0.695
gamitejpratapsingh998
Medium
4,248
230
power of two
class Solution: def isPowerOfTwo(self, n: int) -> bool: return n>0 and n&amp;(n-1)==0
https://leetcode.com/problems/power-of-two/discuss/948641/Python-O(1)-Solution
37
Given an integer n, return true if it is a power of two. Otherwise, return false. An integer n is a power of two, if there exists an integer x such that n == 2x. Example 1: Input: n = 1 Output: true Explanation: 20 = 1 Example 2: Input: n = 16 Output: true Explanation: 24 = 16 Example 3: Input: n = 3 Output: false Constraints: -231 <= n <= 231 - 1 Follow up: Could you solve it without loops/recursion?
Python O(1) Solution
2,400
power-of-two
0.457
lokeshsenthilkumar
Easy
4,273
231
number of digit one
class Solution: def countDigitOne(self, n: int) -> int: #O(logn) mathematical solution #intervals of new 1s: 0-9, 10-99, 100-999, 1000,9999... #each interval yields 1,10,100,etc. new '1's respectively #first and foremost, we want to check how many of each interval repeats #conditions for FULL yield when curr%upper bound+1: 1 <=, 19 <=, 199 <=... #conditions for PARTIAL yielf when curr%upper bound+1: None, 10 <= < 19, 100 <= < 199, 1000 <= < 1999 ... ans = 0 for i in range(len(str(n))): curr = 10**(i+1) hi,lo = int('1'+'9'*i), int('1'+'0'*i) ans += (n//curr) * 10**i if (pot:=n%curr) >= hi: ans += 10**i elif lo <= pot < hi: ans += pot - lo + 1 return ans
https://leetcode.com/problems/number-of-digit-one/discuss/1655517/Python3-O(9)-Straight-Math-Solution
1
Given an integer n, count the total number of digit 1 appearing in all non-negative integers less than or equal to n. Example 1: Input: n = 13 Output: 6 Example 2: Input: n = 0 Output: 0 Constraints: 0 <= n <= 109
Python3 O(9) Straight Math Solution
341
number-of-digit-one
0.342
terrysu64
Hard
4,333
233
palindrome linked list
class Solution: def isPalindrome(self, head: Optional[ListNode]) -> bool: def reverse(node): prev = None while node: next_node = node.next node.next = prev prev, node = node, next_node return prev slow = head fast = head.next while fast and fast.next: slow = slow.next fast = fast.next.next n1 = head n2 = reverse(slow.next) while n2: if n1.val != n2.val: return False n1 = n1.next n2 = n2.next return True
https://leetcode.com/problems/palindrome-linked-list/discuss/2466200/Python-O(N)O(1)
7
Given the head of a singly linked list, return true if it is a palindrome or false otherwise. Example 1: Input: head = [1,2,2,1] Output: true Example 2: Input: head = [1,2] Output: false Constraints: The number of nodes in the list is in the range [1, 105]. 0 <= Node.val <= 9 Follow up: Could you do it in O(n) time and O(1) space?
Python, O(N)/O(1)
839
palindrome-linked-list
0.496
blue_sky5
Easy
4,344
234
lowest common ancestor of a binary search tree
class Solution: def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode': while True: if root.val > p.val and root.val > q.val: root = root.left elif root.val < p.val and root.val < q.val: root = root.right else: return root
https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree/discuss/1394823/Explained-Easy-Iterative-Python-Solution
55
Given a binary search tree (BST), find the lowest common ancestor (LCA) node of two given nodes in the BST. According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes p and q as the lowest node in T that has both p and q as descendants (where we allow a node to be a descendant of itself).” Example 1: Input: root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 8 Output: 6 Explanation: The LCA of nodes 2 and 8 is 6. Example 2: Input: root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 4 Output: 2 Explanation: The LCA of nodes 2 and 4 is 2, since a node can be a descendant of itself according to the LCA definition. Example 3: Input: root = [2,1], p = 2, q = 1 Output: 2 Constraints: The number of nodes in the tree is in the range [2, 105]. -109 <= Node.val <= 109 All Node.val are unique. p != q p and q will exist in the BST.
Explained Easy Iterative Python Solution
2,000
lowest-common-ancestor-of-a-binary-search-tree
0.604
sevdariklejdi
Medium
4,377
235
lowest common ancestor of a binary tree
class Solution: def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode': if root==None or root.val==p.val or root.val==q.val: return root left=self.lowestCommonAncestor(root.left,p,q) right=self.lowestCommonAncestor(root.right,p,q) if left!=None and right!=None: return root elif left!=None: return left else: return right
https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree/discuss/2539410/python3-simple-Solution
4
Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree. According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes p and q as the lowest node in T that has both p and q as descendants (where we allow a node to be a descendant of itself).” Example 1: Input: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 1 Output: 3 Explanation: The LCA of nodes 5 and 1 is 3. Example 2: Input: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 4 Output: 5 Explanation: The LCA of nodes 5 and 4 is 5, since a node can be a descendant of itself according to the LCA definition. Example 3: Input: root = [1,2], p = 1, q = 2 Output: 1 Constraints: The number of nodes in the tree is in the range [2, 105]. -109 <= Node.val <= 109 All Node.val are unique. p != q p and q will exist in the tree.
python3 simple Solution
251
lowest-common-ancestor-of-a-binary-tree
0.581
pranjalmishra334
Medium
4,399
236
delete node in a linked list
class Solution: def deleteNode(self, node): nextNode = node.next node.val = nextNode.val node.next = nextNode.next
https://leetcode.com/problems/delete-node-in-a-linked-list/discuss/1454184/95.96-faster-and-Simpler-solution-with-Explanation.
6
There is a singly-linked list head and we want to delete a node node in it. You are given the node to be deleted node. You will not be given access to the first node of head. All the values of the linked list are unique, and it is guaranteed that the given node node is not the last node in the linked list. Delete the given node. Note that by deleting the node, we do not mean removing it from memory. We mean: The value of the given node should not exist in the linked list. The number of nodes in the linked list should decrease by one. All the values before node should be in the same order. All the values after node should be in the same order. Custom testing: For the input, you should provide the entire linked list head and the node to be given node. node should not be the last node of the list and should be an actual node in the list. We will build the linked list and pass the node to your function. The output will be the entire list after calling your function. Example 1: Input: head = [4,5,1,9], node = 5 Output: [4,1,9] Explanation: You are given the second node with value 5, the linked list should become 4 -> 1 -> 9 after calling your function. Example 2: Input: head = [4,5,1,9], node = 1 Output: [4,5,9] Explanation: You are given the third node with value 1, the linked list should become 4 -> 5 -> 9 after calling your function. Constraints: The number of the nodes in the given list is in the range [2, 1000]. -1000 <= Node.val <= 1000 The value of each node in the list is unique. The node to be deleted is in the list and is not a tail node.
95.96% faster and Simpler solution with Explanation.
870
delete-node-in-a-linked-list
0.753
AmrinderKaur1
Medium
4,427
237
product of array except self
class Solution: def productExceptSelf(self, nums: List[int]) -> List[int]: leftProducts = [0]*len(nums) # initialize left array rightProducts = [0]*len(nums) # initialize right array leftProducts[0] = 1 # the left most is 1 rightProducts[-1] = 1 # the right most is 1 res = [] # output for i in range(1, len(nums)): leftProducts[i] = leftProducts[i-1]*nums[i-1] rightProducts[len(nums) - i - 1] = rightProducts[len(nums) - i]*nums[len(nums) - i] for i in range(len(nums)): res.append(leftProducts[i]*rightProducts[i]) return res
https://leetcode.com/problems/product-of-array-except-self/discuss/744951/Product-of-array-except-self-Python3-Solution-with-a-Detailed-Explanation
12
Given an integer array nums, return an array answer such that answer[i] is equal to the product of all the elements of nums except nums[i]. The product of any prefix or suffix of nums is guaranteed to fit in a 32-bit integer. You must write an algorithm that runs in O(n) time and without using the division operation. Example 1: Input: nums = [1,2,3,4] Output: [24,12,8,6] Example 2: Input: nums = [-1,1,0,-3,3] Output: [0,0,9,0,0] Constraints: 2 <= nums.length <= 105 -30 <= nums[i] <= 30 The product of any prefix or suffix of nums is guaranteed to fit in a 32-bit integer. Follow up: Can you solve the problem in O(1) extra space complexity? (The output array does not count as extra space for space complexity analysis.)
Product of array except self - Python3 Solution with a Detailed Explanation
1,200
product-of-array-except-self
0.648
peyman_np
Medium
4,452
238
sliding window maximum
class Solution: def maxSlidingWindow(self, nums: List[int], k: int) -> List[int]: res = [] window = collections.deque() for i, num in enumerate(nums): while window and num >= nums[window[-1]]: window.pop() window.append(i) if i + 1 >= k: res.append(nums[window[0]]) if i - window[0] + 1 == k: window.popleft() return res
https://leetcode.com/problems/sliding-window-maximum/discuss/1624633/Python-3-O(n)
3
You are given an array of integers nums, 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 max sliding window. Example 1: Input: nums = [1,3,-1,-3,5,3,6,7], k = 3 Output: [3,3,5,5,6,7] Explanation: Window position Max --------------- ----- [1 3 -1] -3 5 3 6 7 3 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 5 1 3 -1 -3 [5 3 6] 7 6 1 3 -1 -3 5 [3 6 7] 7 Example 2: Input: nums = [1], k = 1 Output: [1] Constraints: 1 <= nums.length <= 105 -104 <= nums[i] <= 104 1 <= k <= nums.length
Python 3 O(n)
772
sliding-window-maximum
0.466
dereky4
Hard
4,510
239
search a 2d matrix ii
class Solution: def searchMatrix(self, mat: List[List[int]], target: int) -> bool: m=len(mat) n=len(mat[0]) i=m-1 j=0 while i>=0 and j<n: if mat[i][j]==target: return True elif mat[i][j]<target: j+=1 else: i-=1 return False
https://leetcode.com/problems/search-a-2d-matrix-ii/discuss/2324351/PYTHON-oror-EXPLAINED-oror
48
Write an efficient algorithm that searches for a value target in an m x n integer matrix matrix. This matrix has the following properties: Integers in each row are sorted in ascending from left to right. Integers in each column are sorted in ascending from top to bottom. Example 1: Input: matrix = [[1,4,7,11,15],[2,5,8,12,19],[3,6,9,16,22],[10,13,14,17,24],[18,21,23,26,30]], target = 5 Output: true Example 2: Input: matrix = [[1,4,7,11,15],[2,5,8,12,19],[3,6,9,16,22],[10,13,14,17,24],[18,21,23,26,30]], target = 20 Output: false Constraints: m == matrix.length n == matrix[i].length 1 <= n, m <= 300 -109 <= matrix[i][j] <= 109 All the integers in each row are sorted in ascending order. All the integers in each column are sorted in ascending order. -109 <= target <= 109
✔️ PYTHON || EXPLAINED || ; ]
1,700
search-a-2d-matrix-ii
0.507
karan_8082
Medium
4,542
240
different ways to add parentheses
class Solution(object): def diffWaysToCompute(self, s, memo=dict()): if s in memo: return memo[s] if s.isdigit(): # base case return [int(s)] calculate = {'*': lambda x, y: x * y, '+': lambda x, y: x + y, '-': lambda x, y: x - y } result = [] for i, c in enumerate(s): if c in '+-*': left = self.diffWaysToCompute(s[:i], memo) right = self.diffWaysToCompute(s[i+1:], memo) for l in left: for r in right: result.append(calculate[c](l, r)) memo[s] = result return result
https://leetcode.com/problems/different-ways-to-add-parentheses/discuss/2392799/Python3-Divide-and-Conquer%3A-Recursion-%2B-Memoization
4
Given a string expression of numbers and operators, return all possible results from computing all the different possible ways to group numbers and operators. You may return the answer in any order. The test cases are generated such that the output values fit in a 32-bit integer and the number of different results does not exceed 104. Example 1: Input: expression = "2-1-1" Output: [0,2] Explanation: ((2-1)-1) = 0 (2-(1-1)) = 2 Example 2: Input: expression = "2*3-4*5" Output: [-34,-14,-10,-10,10] Explanation: (2*(3-(4*5))) = -34 ((2*3)-(4*5)) = -14 ((2*(3-4))*5) = -10 (2*((3-4)*5)) = -10 (((2*3)-4)*5) = 10 Constraints: 1 <= expression.length <= 20 expression consists of digits and the operator '+', '-', and '*'. All the integer values in the input expression are in the range [0, 99].
[Python3] Divide and Conquer: Recursion + Memoization
156
different-ways-to-add-parentheses
0.633
mhpd
Medium
4,589
241
valid anagram
class Solution: def isAnagram(self, s: str, t: str) -> bool: tracker = collections.defaultdict(int) for x in s: tracker[x] += 1 for x in t: tracker[x] -= 1 return all(x == 0 for x in tracker.values())
https://leetcode.com/problems/valid-anagram/discuss/433680/Python-3-O(n)-Faster-than-98.39-Memory-usage-less-than-100
69
Given two strings s and t, return true if t is an anagram of s, and false otherwise. 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 = "anagram", t = "nagaram" Output: true Example 2: Input: s = "rat", t = "car" Output: false Constraints: 1 <= s.length, t.length <= 5 * 104 s and t consist of lowercase English letters. Follow up: What if the inputs contain Unicode characters? How would you adapt your solution to such a case?
Python 3 - O(n) - Faster than 98.39%, Memory usage less than 100%
18,500
valid-anagram
0.628
mmbhatk
Easy
4,618
242
binary tree paths
class Solution: def binaryTreePaths(self, R: TreeNode) -> List[str]: A, P = [], [] def dfs(N): if N == None: return P.append(N.val) if (N.left,N.right) == (None,None): A.append('->'.join(map(str,P))) else: dfs(N.left), dfs(N.right) P.pop() dfs(R) return A - Junaid Mansuri - Chicago, IL
https://leetcode.com/problems/binary-tree-paths/discuss/484118/Python-3-(beats-~100)-(nine-lines)-(DFS)
7
Given the root of a binary tree, return all root-to-leaf paths in any order. A leaf is a node with no children. Example 1: Input: root = [1,2,3,null,5] Output: ["1->2->5","1->3"] Example 2: Input: root = [1] Output: ["1"] Constraints: The number of nodes in the tree is in the range [1, 100]. -100 <= Node.val <= 100
Python 3 (beats ~100%) (nine lines) (DFS)
1,100
binary-tree-paths
0.607
junaidmansuri
Easy
4,672
257
add digits
class Solution(object): def addDigits(self, num): while num > 9: num = num % 10 + num // 10 return num
https://leetcode.com/problems/add-digits/discuss/2368005/Very-Easy-100-(Fully-Explained)(Java-C%2B%2B-Python-JS-C-Python3)
13
Given an integer num, repeatedly add all its digits until the result has only one digit, and return it. Example 1: Input: num = 38 Output: 2 Explanation: The process is 38 --> 3 + 8 --> 11 11 --> 1 + 1 --> 2 Since 2 has only one digit, return it. Example 2: Input: num = 0 Output: 0 Constraints: 0 <= num <= 231 - 1 Follow up: Could you do it without any loop/recursion in O(1) runtime?
Very Easy 100% (Fully Explained)(Java, C++, Python, JS, C, Python3)
484
add-digits
0.635
PratikSen07
Easy
4,696
258
single number iii
class Solution: def singleNumber(self, nums: List[int]) -> List[int]: dc=defaultdict(lambda:0) for a in(nums): dc[a]+=1 ans=[] for a in dc: if(dc[a]==1): ans.append(a) return ans
https://leetcode.com/problems/single-number-iii/discuss/2828366/brute-force-with-dictnory
5
Given an integer array nums, in which exactly two elements appear only once and all the other elements appear exactly twice. Find the two elements that appear only once. You can return the answer in any order. You must write an algorithm that runs in linear runtime complexity and uses only constant extra space. Example 1: Input: nums = [1,2,1,3,2,5] Output: [3,5] Explanation: [5, 3] is also a valid answer. Example 2: Input: nums = [-1,0] Output: [-1,0] Example 3: Input: nums = [0,1] Output: [1,0] Constraints: 2 <= nums.length <= 3 * 104 -231 <= nums[i] <= 231 - 1 Each integer in nums will appear twice, only two integers will appear once.
brute force with dictnory
30
single-number-iii
0.675
droj
Medium
4,754
260
ugly number
class Solution: def isUgly(self, num: int) -> bool: if num == 0: return False while num % 5 == 0: num /= 5 while num % 3 == 0: num /= 3 while num % 2 == 0: num /= 2 return num == 1 - Junaid Mansuri
https://leetcode.com/problems/ugly-number/discuss/336227/Solution-in-Python-3-(beats-~99)-(five-lines)
18
An ugly number is a positive integer whose prime factors are limited to 2, 3, and 5. Given an integer n, return true if n is an ugly number. Example 1: Input: n = 6 Output: true Explanation: 6 = 2 × 3 Example 2: Input: n = 1 Output: true Explanation: 1 has no prime factors, therefore all of its prime factors are limited to 2, 3, and 5. Example 3: Input: n = 14 Output: false Explanation: 14 is not ugly since it includes the prime factor 7. Constraints: -231 <= n <= 231 - 1
Solution in Python 3 (beats ~99%) (five lines)
2,600
ugly-number
0.426
junaidmansuri
Easy
4,785
263
ugly number ii
class Solution: def nthUglyNumber(self, n: int) -> int: k = [0] * n t1 = t2 = t3 = 0 k[0] = 1 for i in range(1,n): k[i] = min(k[t1]*2,k[t2]*3,k[t3]*5) if(k[i] == k[t1]*2): t1 += 1 if(k[i] == k[t2]*3): t2 += 1 if(k[i] == k[t3]*5): t3 += 1 return k[n-1]
https://leetcode.com/problems/ugly-number-ii/discuss/556314/Python-Simple-DP-9-Lines
23
An ugly number is a positive integer whose prime factors are limited to 2, 3, and 5. Given an integer n, return the nth ugly number. Example 1: Input: n = 10 Output: 12 Explanation: [1, 2, 3, 4, 5, 6, 8, 9, 10, 12] is the sequence of the first 10 ugly numbers. Example 2: Input: n = 1 Output: 1 Explanation: 1 has no prime factors, therefore all of its prime factors are limited to 2, 3, and 5. Constraints: 1 <= n <= 1690
[Python] Simple DP 9 Lines
1,100
ugly-number-ii
0.462
mazz272727
Medium
4,839
264
missing number
class Solution: def missingNumber(self, nums: List[int]) -> int: return (len(nums) * (len(nums) + 1))//2 - sum(nums)
https://leetcode.com/problems/missing-number/discuss/2081185/Python-Easy-One-liners-with-Explanation
23
Given an array nums containing n distinct numbers in the range [0, n], return the only number in the range that is missing from the array. Example 1: Input: nums = [3,0,1] Output: 2 Explanation: n = 3 since there are 3 numbers, so all numbers are in the range [0,3]. 2 is the missing number in the range since it does not appear in nums. Example 2: Input: nums = [0,1] Output: 2 Explanation: n = 2 since there are 2 numbers, so all numbers are in the range [0,2]. 2 is the missing number in the range since it does not appear in nums. Example 3: Input: nums = [9,6,4,2,3,5,7,0,1] Output: 8 Explanation: n = 9 since there are 9 numbers, so all numbers are in the range [0,9]. 8 is the missing number in the range since it does not appear in nums. Constraints: n == nums.length 1 <= n <= 104 0 <= nums[i] <= n All the numbers of nums are unique. Follow up: Could you implement a solution using only O(1) extra space complexity and O(n) runtime complexity?
✅ Python Easy One liners with Explanation
2,000
missing-number
0.617
constantine786
Easy
4,860
268
integer to english words
class Solution: def numberToWords(self, num: int) -> str: mp = {1: "One", 11: "Eleven", 10: "Ten", 2: "Two", 12: "Twelve", 20: "Twenty", 3: "Three", 13: "Thirteen", 30: "Thirty", 4: "Four", 14: "Fourteen", 40: "Forty", 5: "Five", 15: "Fifteen", 50: "Fifty", 6: "Six", 16: "Sixteen", 60: "Sixty", 7: "Seven", 17: "Seventeen", 70: "Seventy", 8: "Eight", 18: "Eighteen", 80: "Eighty", 9: "Nine", 19: "Nineteen", 90: "Ninety"} def fn(n): """Return English words of n (0-999) in array.""" if not n: return [] elif n < 20: return [mp[n]] elif n < 100: return [mp[n//10*10]] + fn(n%10) else: return [mp[n//100], "Hundred"] + fn(n%100) ans = [] for i, unit in zip((9, 6, 3, 0), ("Billion", "Million", "Thousand", "")): n, num = divmod(num, 10**i) ans.extend(fn(n)) if n and unit: ans.append(unit) return " ".join(ans) or "Zero"
https://leetcode.com/problems/integer-to-english-words/discuss/1990823/JavaC%2B%2BPythonJavaScriptKotlinSwiftO(n)timeBEATS-99.97-MEMORYSPEED-0ms-APRIL-2022
8
Convert a non-negative integer num to its English words representation. Example 1: Input: num = 123 Output: "One Hundred Twenty Three" Example 2: Input: num = 12345 Output: "Twelve Thousand Three Hundred Forty Five" Example 3: Input: num = 1234567 Output: "One Million Two Hundred Thirty Four Thousand Five Hundred Sixty Seven" Constraints: 0 <= num <= 231 - 1
[Java/C++/Python/JavaScript/Kotlin/Swift]O(n)time/BEATS 99.97% MEMORY/SPEED 0ms APRIL 2022
677
integer-to-english-words
0.299
cucerdariancatalin
Hard
4,927
273
h index
class Solution: def hIndex(self, citations: List[int]) -> int: tmp = [0] * (len(citations) + 1) for i in range(len(citations)): if citations[i] > len(citations): tmp[len(citations)] += 1 else: tmp[citations[i]] += 1 sum_ = 0 for i in range(len(tmp) - 1, -1, -1): sum_ += tmp[i] if sum_ >= i: return i
https://leetcode.com/problems/h-index/discuss/785586/Python3-O(n)-without-sorting!
5
Given an array of integers citations where citations[i] is the number of citations a researcher received for their ith paper, return the researcher's h-index. According to the definition of h-index on Wikipedia: The h-index is defined as the maximum value of h such that the given researcher has published at least h papers that have each been cited at least h times. Example 1: Input: citations = [3,0,6,1,5] Output: 3 Explanation: [3,0,6,1,5] means the researcher has 5 papers in total and each of them had received 3, 0, 6, 1, 5 citations respectively. Since the researcher has 3 papers with at least 3 citations each and the remaining two with no more than 3 citations each, their h-index is 3. Example 2: Input: citations = [1,3,1] Output: 1 Constraints: n == citations.length 1 <= n <= 5000 0 <= citations[i] <= 1000
Python3 O(n) without sorting!
489
h-index
0.382
DebbieAlter
Medium
4,949
274
h index ii
class Solution: def hIndex(self, A): n = len(A) l, r = 0, n - 1 while l < r: m = (l + r + 1) // 2 if A[m] > n - m: r = m - 1 else: l = m return n - l - (A[l] < n - l)
https://leetcode.com/problems/h-index-ii/discuss/2729382/Python3-Solution-or-Binary-Search-or-O(logn)
2
Given an array of integers citations where citations[i] is the number of citations a researcher received for their ith paper and citations is sorted in ascending order, return the researcher's h-index. According to the definition of h-index on Wikipedia: The h-index is defined as the maximum value of h such that the given researcher has published at least h papers that have each been cited at least h times. You must write an algorithm that runs in logarithmic time. Example 1: Input: citations = [0,1,3,5,6] Output: 3 Explanation: [0,1,3,5,6] means the researcher has 5 papers in total and each of them had received 0, 1, 3, 5, 6 citations respectively. Since the researcher has 3 papers with at least 3 citations each and the remaining two with no more than 3 citations each, their h-index is 3. Example 2: Input: citations = [1,2,100] Output: 2 Constraints: n == citations.length 1 <= n <= 105 0 <= citations[i] <= 1000 citations is sorted in ascending order.
✔ Python3 Solution | Binary Search | O(logn)
109
h-index-ii
0.374
satyam2001
Medium
4,965
275
first bad version
class Solution: def firstBadVersion(self, n: int) -> int: left = 1 right = n result = 1 while left<=right: mid = (left+right)//2 if isBadVersion(mid) == False: left = mid+1 else: right = mid-1 result = mid return result
https://leetcode.com/problems/first-bad-version/discuss/2700688/Simple-Python-Solution-Using-Binary-Search
25
You are a product manager and currently leading a team to develop a new product. Unfortunately, the latest version of your product fails the quality check. Since each version is developed based on the previous version, all the versions after a bad version are also bad. Suppose you have n versions [1, 2, ..., n] and you want to find out the first bad one, which causes all the following ones to be bad. You are given an API bool isBadVersion(version) which returns whether version is bad. Implement a function to find the first bad version. You should minimize the number of calls to the API. Example 1: Input: n = 5, bad = 4 Output: 4 Explanation: call isBadVersion(3) -> false call isBadVersion(5) -> true call isBadVersion(4) -> true Then 4 is the first bad version. Example 2: Input: n = 1, bad = 1 Output: 1 Constraints: 1 <= bad <= n <= 231 - 1
✔️ Simple Python Solution Using Binary Search 🔥
3,400
first-bad-version
0.43
pniraj657
Easy
4,979
278
perfect squares
class Solution: def isSquare(self, n: int) -> bool: sq = int(math.sqrt(n)) return sq*sq == n def numSquares(self, n: int) -> int: # Lagrange's four-square theorem if self.isSquare(n): return 1 while (n &amp; 3) == 0: n >>= 2 if (n &amp; 7) == 7: return 4 sq = int(math.sqrt(n)) + 1 for i in range(1,sq): if self.isSquare(n - i*i): return 2 return 3
https://leetcode.com/problems/perfect-squares/discuss/376795/100-O(log-n)-Python3-Solution-Lagrange's-four-square-theorem
12
Given an integer n, return the least number of perfect square numbers that sum to n. A perfect square is an integer that is the square of an integer; in other words, it is the product of some integer with itself. For example, 1, 4, 9, and 16 are perfect squares while 3 and 11 are not. Example 1: Input: n = 12 Output: 3 Explanation: 12 = 4 + 4 + 4. Example 2: Input: n = 13 Output: 2 Explanation: 13 = 4 + 9. Constraints: 1 <= n <= 104
100% O(log n) Python3 Solution - Lagrange’s four-square theorem
1,200
perfect-squares
0.526
TCarmic
Medium
4,993
279
expression add operators
class Solution: def addOperators(self, num: str, target: int) -> List[str]: exprs = [] def recurse(idx, value, delta, exp): # base case here if idx == len(num): if value == target: exprs.append("".join(exp)) # the loop will create the current operand and recursively call # the next set of actions to be executed for i in range(idx, len(num)): # this is to avoid cases where the operand starts with a 0 # we need to have a case with just the 0 but not something like # 05, so the condition will return early if we find such cases if num[idx] == '0' and i > idx: return curr = int(num[idx:i+1]) curr_str = num[idx:i+1] # when we start the problem we dont have a preceding operator or operand if idx == 0: recurse(i+1, curr, curr, exp + [curr_str]) else: # We need to do 3 different recursions for each operator # value stores the running value of the expression evaluated so far # the crux of the logic lies in how we use and pass delta # when the operation is '+' or '-' we don't care much about it and can just # add or subtract it from the value # when '*' is involved, we need to follow the precedence relation, # but we have already evaluated the previous operator. We know the # previous operation that was performed and how much it contributed to the value i.e., delta # so, we can revert that operation by subtracting delta from value and reapplying the multiplication recurse(i+1, value+curr, curr, exp + ['+', curr_str]) recurse(i+1, value-curr, -curr, exp + ['-', curr_str]) recurse(i+1, (value-delta)+curr*delta, curr*delta, exp + ['*', curr_str]) recurse(0, 0, 0, []) return exprs
https://leetcode.com/problems/expression-add-operators/discuss/1031229/Python-Simple-heavily-commented-and-accepted-Recursive-Solution
4
Given a string num that contains only digits and an integer target, return all possibilities to insert the binary operators '+', '-', and/or '*' between the digits of num so that the resultant expression evaluates to the target value. Note that operands in the returned expressions should not contain leading zeros. Example 1: Input: num = "123", target = 6 Output: ["1*2*3","1+2+3"] Explanation: Both "1*2*3" and "1+2+3" evaluate to 6. Example 2: Input: num = "232", target = 8 Output: ["2*3+2","2+3*2"] Explanation: Both "2*3+2" and "2+3*2" evaluate to 8. Example 3: Input: num = "3456237490", target = 9191 Output: [] Explanation: There are no expressions that can be created from "3456237490" to evaluate to 9191. Constraints: 1 <= num.length <= 10 num consists of only digits. -231 <= target <= 231 - 1
[Python] Simple, heavily commented and accepted Recursive Solution
354
expression-add-operators
0.392
gokivego
Hard
5,046
282
move zeroes
class Solution(object): def moveZeroes(self, nums): i=0 n = len(nums) while i <n: if nums[i]==0: nums.pop(i) nums.append(0) n-=1 else: i+=1
https://leetcode.com/problems/move-zeroes/discuss/404010/Python-easy-solution
16
Given an integer array nums, move all 0's to the end of it while maintaining the relative order of the non-zero elements. Note that you must do this in-place without making a copy of the array. Example 1: Input: nums = [0,1,0,3,12] Output: [1,3,12,0,0] Example 2: Input: nums = [0] Output: [0] Constraints: 1 <= nums.length <= 104 -231 <= nums[i] <= 231 - 1 Follow up: Could you minimize the total number of operations done?
Python easy solution
2,600
move-zeroes
0.614
saffi
Easy
5,056
283
find the duplicate number
class Solution: def findDuplicate(self, nums: List[int]) -> int: slow = fast = ans = 0 while True: slow = nums[slow] fast = nums[nums[fast]] if slow == fast: break while ans != slow: ans = nums[ans] slow = nums[slow] return ans
https://leetcode.com/problems/find-the-duplicate-number/discuss/650942/Proof-of-Floyd's-cycle-detection-algorithm-Find-the-Duplicate-Number
20
Given an array of integers nums containing n + 1 integers where each integer is in the range [1, n] inclusive. There is only one repeated number in nums, return this repeated number. You must solve the problem without modifying the array nums and uses only constant extra space. Example 1: Input: nums = [1,3,4,2,2] Output: 2 Example 2: Input: nums = [3,1,3,4,2] Output: 3 Example 3: Input: nums = [3,3,3,3,3] Output: 3 Constraints: 1 <= n <= 105 nums.length == n + 1 1 <= nums[i] <= n All the integers in nums appear only once except for precisely one integer which appears two or more times. Follow up: How can we prove that at least one duplicate number must exist in nums? Can you solve the problem in linear runtime complexity?
Proof of Floyd's cycle detection algorithm - Find the Duplicate Number
2,400
find-the-duplicate-number
0.591
r0bertz
Medium
5,101
287
game of life
class Solution: def gameOfLife(self, board: List[List[int]]) -> None: """ Do not return anything, modify board in-place instead. """ def is_neighbor(board, i, j): return (0 <= i < len(board)) and (0 <= j < len(board[0])) and board[i][j] % 10 == 1 directions = [(0, 1), (0, -1), (1, 0), (-1, 0), (1, 1), (1, -1), (-1, 1), (-1, -1)] for i in range(len(board)): for j in range(len(board[0])): for d in directions: board[i][j] += 10 if is_neighbor(board, i + d[0], j + d[1]) else 0 # if adj cell is neighbor, add 10 for i in range(len(board)): for j in range(len(board[0])): neighbors = board[i][j] // 10 # count of neighbors is_live = board[i][j] % 10 == 1 # state is live or not if is_live: # live(1) if neighbors < 2: # Rule 1 board[i][j] = 0 elif neighbors > 3: # Rule 3 board[i][j] = 0 else: # Rule 2 board[i][j] = 1 else: # dead(0) if neighbors == 3: # Rule 4 board[i][j] = 1 else: board[i][j] = 0
https://leetcode.com/problems/game-of-life/discuss/468108/Use-the-tens-digit-as-a-counter-Python-O(1)-Space-O(mn)-Time
4
According to Wikipedia's article: "The Game of Life, also known simply as Life, is a cellular automaton devised by the British mathematician John Horton Conway in 1970." The board is made up of an m x n grid of cells, where each cell has an initial state: live (represented by a 1) or dead (represented by a 0). Each cell interacts with its eight neighbors (horizontal, vertical, diagonal) using the following four rules (taken from the above Wikipedia article): Any live cell with fewer than two live neighbors dies as if caused by under-population. Any live cell with two or three live neighbors lives on to the next generation. Any live cell with more than three live neighbors dies, as if by over-population. Any dead cell with exactly three live neighbors becomes a live cell, as if by reproduction. The next state is created by applying the above rules simultaneously to every cell in the current state, where births and deaths occur simultaneously. Given the current state of the m x n grid board, return the next state. Example 1: Input: board = [[0,1,0],[0,0,1],[1,1,1],[0,0,0]] Output: [[0,0,0],[1,0,1],[0,1,1],[0,1,0]] Example 2: Input: board = [[1,1],[1,0]] Output: [[1,1],[1,1]] Constraints: m == board.length n == board[i].length 1 <= m, n <= 25 board[i][j] is 0 or 1. Follow up: Could you solve it in-place? Remember that the board needs to be updated simultaneously: You cannot update some cells first and then use their updated values to update other cells. In this question, we represent the board using a 2D array. In principle, the board is infinite, which would cause problems when the active area encroaches upon the border of the array (i.e., live cells reach the border). How would you address these problems?
Use the tens digit as a counter, Python O(1) Space, O(mn) Time
104
game-of-life
0.668
Moooooon
Medium
5,156
289
word pattern
class Solution: def wordPattern(self, pattern: str, s: str) -> bool: li = s.split(' ') di = {} if len(li) != len(pattern): return False for i, val in enumerate(pattern): if val in di and di[val] != li[i]: return False elif val not in di and li[i] in di.values(): return False elif val not in di: di[val] = li[i] return True
https://leetcode.com/problems/word-pattern/discuss/1696590/Simple-Python-Solution-oror-Faster-than-99.34
4
Given a pattern and a string s, find if s follows the same pattern. Here follow means a full match, such that there is a bijection between a letter in pattern and a non-empty word in s. Example 1: Input: pattern = "abba", s = "dog cat cat dog" Output: true Example 2: Input: pattern = "abba", s = "dog cat cat fish" Output: false Example 3: Input: pattern = "aaaa", s = "dog cat cat dog" Output: false Constraints: 1 <= pattern.length <= 300 pattern contains only lower-case English letters. 1 <= s.length <= 3000 s contains only lowercase English letters and spaces ' '. s does not contain any leading or trailing spaces. All the words in s are separated by a single space.
Simple Python Solution || Faster than 99.34%
509
word-pattern
0.404
KiranUpase
Easy
5,202
290
nim game
class Solution: def canWinNim(self, n: int) -> bool: if n <= 3: return True new_size = n + 1 memo = [False] * (new_size) for i in range(4): memo[i] = True for i in range(4,new_size): for j in range(1,4): if memo[i] == True: break if memo[i-j] == True: memo[i] = False else: memo[i] = True return memo[n]
https://leetcode.com/problems/nim-game/discuss/1141120/Bottom-up-DP-python
9
You are playing the following Nim Game with your friend: Initially, there is a heap of stones on the table. You and your friend will alternate taking turns, and you go first. On each turn, the person whose turn it is will remove 1 to 3 stones from the heap. The one who removes the last stone is the winner. Given n, the number of stones in the heap, return true if you can win the game assuming both you and your friend play optimally, otherwise return false. Example 1: Input: n = 4 Output: false Explanation: These are the possible outcomes: 1. You remove 1 stone. Your friend removes 3 stones, including the last stone. Your friend wins. 2. You remove 2 stones. Your friend removes 2 stones, including the last stone. Your friend wins. 3. You remove 3 stones. Your friend removes the last stone. Your friend wins. In all outcomes, your friend wins. Example 2: Input: n = 1 Output: true Example 3: Input: n = 2 Output: true Constraints: 1 <= n <= 231 - 1
Bottom-up DP python
725
nim-game
0.559
lywc
Easy
5,249
292
bulls and cows
class Solution: def getHint(self, secret: str, guess: str) -> str: # The main idea is to understand that cow cases contain the bull cases # This loop will take care of "bull" cases bull=0 for i in range(len(secret)): bull += int(secret[i] == guess[i]) # This loop will take care of "cow" cases cows=0 for c in set(secret): cows += min(secret.count(c), guess.count(c)) return f"{bull}A{cows-bull}B"
https://leetcode.com/problems/bulls-and-cows/discuss/563661/Fast-and-easy-to-understand-Python-solution-O(n)
14
You are playing the Bulls and Cows game with your friend. You write down a secret number and ask your friend to guess what the number is. When your friend makes a guess, you provide a hint with the following info: The number of "bulls", which are digits in the guess that are in the correct position. The number of "cows", which are digits in the guess that are in your secret number but are located in the wrong position. Specifically, the non-bull digits in the guess that could be rearranged such that they become bulls. Given the secret number secret and your friend's guess guess, return the hint for your friend's guess. The hint should be formatted as "xAyB", where x is the number of bulls and y is the number of cows. Note that both secret and guess may contain duplicate digits. Example 1: Input: secret = "1807", guess = "7810" Output: "1A3B" Explanation: Bulls are connected with a '|' and cows are underlined: "1807" | "7810" Example 2: Input: secret = "1123", guess = "0111" Output: "1A1B" Explanation: Bulls are connected with a '|' and cows are underlined: "1123" "1123" | or | "0111" "0111" Note that only one of the two unmatched 1s is counted as a cow since the non-bull digits can only be rearranged to allow one 1 to be a bull. Constraints: 1 <= secret.length, guess.length <= 1000 secret.length == guess.length secret and guess consist of digits only.
Fast and easy to understand Python solution O(n)
983
bulls-and-cows
0.487
mista2311
Medium
5,269
299
longest increasing subsequence
class Solution: # Suppose, for example: # nums = [1,8,4,5,3,7], # for which the longest strictly increasing subsequence is arr = [1,4,5,7], # giving len(arr) = 4 as the answer # # Here's the plan: # 1) Initiate arr = [num[0]], which in this example means arr = [1] # # 2) Iterate through nums. 2a) If n in nums is greater than arr[-1], append n to arr. 2b) If # not, determine the furthest position in arr at which n could be placed so that arr # remains strictly increasing, and overwrite the element at that position in arr with n. # 3) Once completed, return the length of arr. # Here's the iteration for the example: # nums = [ _1_, 8,4,5,3,7] arr = [1] (initial step) # nums = [1, _8_, 4,5,3,7] arr = [1, 8] (8 > 1, so append 8) # nums = [1,8, _4_, 5,3,7] arr = [1, 4] (4 < 8, so overwrite 8) # nums = [1_8,4, _5_, 3,7] arr = [1, 4, 5] (5 > 4, so append 5) # nums = [1_8,4,5, _3_, 7] arr = [1, 3, 5] (3 < 5, so overwrite 4) # nums = [1_8,4,5,3, _7_ ] arr = [1, 3, 5, 7] (7 > 5, so append 7) # Notice that arr is not the sequence given above as the correct seq. The ordering for [1,3,5,7] # breaks the "no changing the order" rule. Cheating? Maybe... However len(arr) = 4 is the # correct answer. Overwriting 4 with 3 did not alter the sequence's length. def lengthOfLIS(self, nums: list[int]) -> int: arr = [nums.pop(0)] # <-- 1) initial step for n in nums: # <-- 2) iterate through nums if n > arr[-1]: # <-- 2a) arr.append(n) else: # <-- 2b) arr[bisect_left(arr, n)] = n return len(arr) # <-- 3) return the length of arr
https://leetcode.com/problems/longest-increasing-subsequence/discuss/2395570/Python3-oror-7-lines-binSearch-cheating-wexplanation-oror-TM%3A-9482
45
Given an integer array nums, return the length of the longest strictly increasing subsequence . Example 1: Input: nums = [10,9,2,5,3,7,101,18] Output: 4 Explanation: The longest increasing subsequence is [2,3,7,101], therefore the length is 4. Example 2: Input: nums = [0,1,0,3,2,3] Output: 4 Example 3: Input: nums = [7,7,7,7,7,7,7] Output: 1 Constraints: 1 <= nums.length <= 2500 -104 <= nums[i] <= 104 Follow up: Can you come up with an algorithm that runs in O(n log(n)) time complexity?
Python3 || 7 lines, binSearch, cheating, w/explanation || T/M: 94%/82%
4,100
longest-increasing-subsequence
0.516
warrenruud
Medium
5,303
300
remove invalid parentheses
class Solution: def removeInvalidParentheses(self, s: str) -> List[str]: def valid(s): l,r=0,0 for c in s: if c=='(': l+=1 elif c==')': if l<=0: r+=1 else: l-=1 return not l and not r res=[] seen=set() level={s} while True: newLevel=set() for word in level: if valid(word): res.append(word) if res: return res for word in level: for i in range(len(word)): if word[i] in '()': newWord=word[:i]+word[i+1:] if newWord not in seen: seen.add(newWord) newLevel.add(newWord) level=newLevel return [""]
https://leetcode.com/problems/remove-invalid-parentheses/discuss/1555755/Easy-to-understand-Python-solution
3
Given a string s that contains parentheses and letters, remove the minimum number of invalid parentheses to make the input string valid. Return a list of unique strings that are valid with the minimum number of removals. You may return the answer in any order. Example 1: Input: s = "()())()" Output: ["(())()","()()()"] Example 2: Input: s = "(a)())()" Output: ["(a())()","(a)()()"] Example 3: Input: s = ")(" Output: [""] Constraints: 1 <= s.length <= 25 s consists of lowercase English letters and parentheses '(' and ')'. There will be at most 20 parentheses in s.
Easy to understand Python 🐍 solution
375
remove-invalid-parentheses
0.471
InjySarhan
Hard
5,356
301
additive number
class Solution: def isAdditiveNumber(self, s: str) -> bool: n = len(s) for i in range(1, n): # Choose the length of first number # If length of 1st number is > 1 and starts with 0 -- skip if i != 1 and s[0] == '0': continue for j in range(1, n): # Choose the length of second number # If length of 2nd number is > 1 and starts with 0 -- skip if j != 1 and s[i] == '0': continue # If the total length of 1st and 2nd number >= n -- skip if i + j >= n: break # Just use the brute force approach a = int(s[0: i]) b = int(s[i: i+j]) d = i+j while d < n: c = a + b t = str(c) if s[d: d + len(t)] != t: break d += len(t) a = b b = c if d == n: return True return False
https://leetcode.com/problems/additive-number/discuss/2764371/Python-solution-with-complete-explanation-and-code
0
An additive number is a string whose digits can form an additive sequence. A valid additive sequence should contain at least three numbers. Except for the first two numbers, each subsequent number in the sequence must be the sum of the preceding two. Given a string containing only digits, return true if it is an additive number or false otherwise. Note: Numbers in the additive sequence cannot have leading zeros, so sequence 1, 2, 03 or 1, 02, 3 is invalid. Example 1: Input: "112358" Output: true Explanation: The digits can form an additive sequence: 1, 1, 2, 3, 5, 8. 1 + 1 = 2, 1 + 2 = 3, 2 + 3 = 5, 3 + 5 = 8 Example 2: Input: "199100199" Output: true Explanation: The additive sequence is: 1, 99, 100, 199. 1 + 99 = 100, 99 + 100 = 199 Constraints: 1 <= num.length <= 35 num consists only of digits. Follow up: How would you handle overflow for very large input integers?
Python solution with complete explanation and code
11
additive-number
0.309
smit5300
Medium
5,364
306
best time to buy and sell stock with cooldown
class Solution: def maxProfit(self, prices: List[int]) -> int: n = len(prices) dp = [[0 for i in range(2)] for i in range(n+2)] dp[n][0] = dp[n][1] = 0 ind = n-1 while(ind>=0): for buy in range(2): if(buy): profit = max(-prices[ind] + dp[ind+1][0], 0 + dp[ind+1][1]) else: profit = max(prices[ind] + dp[ind+2][1], 0 + dp[ind+1][0]) dp[ind][buy] = profit ind -= 1 return dp[0][1]
https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-cooldown/discuss/2132119/Python-or-Easy-DP-or
4
You are given an array prices where prices[i] is the price of a given stock on the ith day. Find the maximum profit you can achieve. You may complete as many transactions as you like (i.e., buy one and sell one share of the stock multiple times) with the following restrictions: After you sell your stock, you cannot buy stock on the next day (i.e., cooldown one day). Note: You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again). Example 1: Input: prices = [1,2,3,0,2] Output: 3 Explanation: transactions = [buy, sell, cooldown, buy, sell] Example 2: Input: prices = [1] Output: 0 Constraints: 1 <= prices.length <= 5000 0 <= prices[i] <= 1000
Python | Easy DP |
166
best-time-to-buy-and-sell-stock-with-cooldown
0.546
LittleMonster23
Medium
5,369
309
minimum height trees
class Solution: def findMinHeightTrees(self, n: int, edges: List[List[int]]) -> List[int]: if n == 1: return [0] graph = {i:[] for i in range(n)} for u, v in edges: graph[u].append(v) graph[v].append(u) leaves = [] for node in graph: if len(graph[node]) == 1: leaves.append(node) while len(graph) > 2: new_leaves = [] for leaf in leaves: nei = graph[leaf].pop() del graph[leaf] graph[nei].remove(leaf) if len(graph[nei]) == 1: new_leaves.append(nei) leaves = new_leaves return leaves
https://leetcode.com/problems/minimum-height-trees/discuss/1753794/Python-easy-to-read-and-understand-or-reverse-topological-sort
7
A tree is an undirected graph in which any two vertices are connected by exactly one path. In other words, any connected graph without simple cycles is a tree. Given a tree of n nodes labelled from 0 to n - 1, and an array of n - 1 edges where edges[i] = [ai, bi] indicates that there is an undirected edge between the two nodes ai and bi in the tree, you can choose any node of the tree as the root. When you select a node x as the root, the result tree has height h. Among all possible rooted trees, those with minimum height (i.e. min(h)) are called minimum height trees (MHTs). Return a list of all MHTs' root labels. You can return the answer in any order. The height of a rooted tree is the number of edges on the longest downward path between the root and a leaf. Example 1: Input: n = 4, edges = [[1,0],[1,2],[1,3]] Output: [1] Explanation: As shown, the height of the tree is 1 when the root is the node with label 1 which is the only MHT. Example 2: Input: n = 6, edges = [[3,0],[3,1],[3,2],[3,4],[5,4]] Output: [3,4] Constraints: 1 <= n <= 2 * 104 edges.length == n - 1 0 <= ai, bi < n ai != bi All the pairs (ai, bi) are distinct. The given input is guaranteed to be a tree and there will be no repeated edges.
Python easy to read and understand | reverse topological sort
336
minimum-height-trees
0.385
sanial2001
Medium
5,399
310
burst balloons
class Solution(object): def maxCoins(self, nums): n=len(nums) nums.insert(n,1) nums.insert(0,1) self.dp={} return self.dfs(1,nums,n) def dfs(self,strt,nums,end): ans=0 if strt>end: return 0 if (strt,end) in self.dp: return self.dp[(strt,end)] for i in range(strt,end+1): lmax=self.dfs(strt,nums,i-1) rmax=self.dfs(i+1,nums,end) curr_coins=nums[strt-1]*nums[i]*nums[end+1]+lmax+rmax ans=max(ans,curr_coins) self.dp[(strt,end)]=ans return self.dp[(strt,end)]
https://leetcode.com/problems/burst-balloons/discuss/1477014/Python3-or-Top-down-Approach
2
You are given n balloons, indexed from 0 to n - 1. Each balloon is painted with a number on it represented by an array nums. You are asked to burst all the balloons. If you burst the ith balloon, you will get nums[i - 1] * nums[i] * nums[i + 1] coins. If i - 1 or i + 1 goes out of bounds of the array, then treat it as if there is a balloon with a 1 painted on it. Return the maximum coins you can collect by bursting the balloons wisely. Example 1: Input: nums = [3,1,5,8] Output: 167 Explanation: nums = [3,1,5,8] --> [3,5,8] --> [3,8] --> [8] --> [] coins = 3*1*5 + 3*5*8 + 1*3*8 + 1*8*1 = 167 Example 2: Input: nums = [1,5] Output: 10 Constraints: n == nums.length 1 <= n <= 300 0 <= nums[i] <= 100
[Python3] | Top-down Approach
269
burst-balloons
0.568
swapnilsingh421
Hard
5,412
312
super ugly number
class Solution: def nthSuperUglyNumber(self, n: int, primes: List[int]) -> int: hp=[1] dc={1} i=1 while(n): mn=heapq.heappop(hp) if(n==1): return mn for p in primes: newno=mn*p if(newno in dc): continue heapq.heappush(hp,newno) dc.add(newno) n-=1
https://leetcode.com/problems/super-ugly-number/discuss/2828266/heapq-did-the-job
5
A super ugly number is a positive integer whose prime factors are in the array primes. Given an integer n and an array of integers primes, return the nth super ugly number. The nth super ugly number is guaranteed to fit in a 32-bit signed integer. Example 1: Input: n = 12, primes = [2,7,13,19] Output: 32 Explanation: [1,2,4,7,8,13,14,16,19,26,28,32] is the sequence of the first 12 super ugly numbers given primes = [2,7,13,19]. Example 2: Input: n = 1, primes = [2,3,5] Output: 1 Explanation: 1 has no prime factors, therefore all of its prime factors are in the array primes = [2,3,5]. Constraints: 1 <= n <= 105 1 <= primes.length <= 100 2 <= primes[i] <= 1000 primes[i] is guaranteed to be a prime number. All the values of primes are unique and sorted in ascending order.
heapq did the job
40
super-ugly-number
0.458
droj
Medium
5,421
313
count of smaller numbers after self
class Solution: # Here's the plan: # 1) Make arr, a sorted copy of the list nums. # 2) iterate through nums. For each element num in nums: # 2a) use a binary search to determine the count of elements # in the arr that are less than num. # 2b) append that count to the answer list # 2c) delete num from arr # 3) return the ans list # # For example, suppose nums = [5,2,6,1] Then arr = [1,2,5,6]. # num = 5 => binsearch: arr = [1,2,/\5,6], i = 2 => ans = [2,_,_,_], del 5 # num = 2 => binsearch: arr = [1,/\2,6], i = 1 => ans = [2,1,_,_], del 2 # num = 6 => binsearch: arr = [1,/\6], i = 1 => ans = [2,1,1,_], del 6 # num = 1 => binsearch: arr = [/\1], i = 0 => ans = [2,1,1,0], del 1 def countSmaller(self, nums: List[int]) -> List[int]: arr, ans = sorted(nums), [] # <-- 1) for num in nums: i = bisect_left(arr,num) # <-- 2a) ans.append(i) # <-- 2b) del arr[i] # <-- 2c) return ans # <-- 3)
https://leetcode.com/problems/count-of-smaller-numbers-after-self/discuss/2320000/Python3.-oror-binSearch-6-lines-w-explanation-oror-TM%3A-9784
27
Given an integer array nums, return an integer array counts where counts[i] is the number of smaller elements to the right of nums[i]. Example 1: Input: nums = [5,2,6,1] Output: [2,1,1,0] Explanation: To the right of 5 there are 2 smaller elements (2 and 1). To the right of 2 there is only 1 smaller element (1). To the right of 6 there is 1 smaller element (1). To the right of 1 there is 0 smaller element. Example 2: Input: nums = [-1] Output: [0] Example 3: Input: nums = [-1,-1] Output: [0,0] Constraints: 1 <= nums.length <= 105 -104 <= nums[i] <= 104
Python3. || binSearch 6 lines, w/ explanation || T/M: 97%/84%
3,000
count-of-smaller-numbers-after-self
0.428
warrenruud
Hard
5,429
315
remove duplicate letters
class Solution: def removeDuplicateLetters(self, s: str) -> str: stack = [] for idx, character in enumerate(s): if not stack: stack.append(character) elif character in stack: continue else: while stack and (character < stack[-1]): if stack[-1] in s[idx + 1:]: _ = stack.pop() else: break stack.append(character) return ''.join(stack)
https://leetcode.com/problems/remove-duplicate-letters/discuss/1687144/Python-3-Simple-solution-using-a-stack-and-greedy-approach-(32ms-14.4MB)
5
Given a string s, remove duplicate letters so that every letter appears once and only once. You must make sure your result is the smallest in lexicographical order among all possible results. Example 1: Input: s = "bcabc" Output: "abc" Example 2: Input: s = "cbacdcbc" Output: "acdb" Constraints: 1 <= s.length <= 104 s consists of lowercase English letters. Note: This question is the same as 1081: https://leetcode.com/problems/smallest-subsequence-of-distinct-characters/
[Python 3] Simple solution using a stack and greedy approach (32ms, 14.4MB)
498
remove-duplicate-letters
0.446
seankala
Medium
5,443
316
maximum product of word lengths
class Solution: def maxProduct(self, words: List[str]) -> int: n=len(words) char_set = [set(words[i]) for i in range(n)] # precompute hashset for each word max_val = 0 for i in range(n): for j in range(i+1, n): if not (char_set[i] &amp; char_set[j]): # if nothing common max_val=max(max_val, len(words[i]) * len(words[j])) return max_val
https://leetcode.com/problems/maximum-product-of-word-lengths/discuss/2085316/Python-or-or-Easy-3-Approaches-explained
57
Given a string array words, return the maximum value of length(word[i]) * length(word[j]) where the two words do not share common letters. If no such two words exist, return 0. Example 1: Input: words = ["abcw","baz","foo","bar","xtfn","abcdef"] Output: 16 Explanation: The two words can be "abcw", "xtfn". Example 2: Input: words = ["a","ab","abc","d","cd","bcd","abcd"] Output: 4 Explanation: The two words can be "ab", "cd". Example 3: Input: words = ["a","aa","aaa","aaaa"] Output: 0 Explanation: No such pair of words. Constraints: 2 <= words.length <= 1000 1 <= words[i].length <= 1000 words[i] consists only of lowercase English letters.
✅ Python | | Easy 3 Approaches explained
3,700
maximum-product-of-word-lengths
0.601
constantine786
Medium
5,463
318
bulb switcher
class Solution: def bulbSwitch(self, n: int) -> int: # Only those bulds with perferct square number index will keep "ON" at last. return int(n**0.5)
https://leetcode.com/problems/bulb-switcher/discuss/535399/PythonJSJavaC%2B%2B-sol-by-perfect-square.-w-Visualization
20
There are n bulbs that are initially off. You first turn on all the bulbs, then you turn off every second bulb. On the third round, you toggle every third bulb (turning on if it's off or turning off if it's on). For the ith round, you toggle every i bulb. For the nth round, you only toggle the last bulb. Return the number of bulbs that are on after n rounds. Example 1: Input: n = 3 Output: 1 Explanation: At first, the three bulbs are [off, off, off]. After the first round, the three bulbs are [on, on, on]. After the second round, the three bulbs are [on, off, on]. After the third round, the three bulbs are [on, off, off]. So you should return 1 because there is only one bulb is on. Example 2: Input: n = 0 Output: 0 Example 3: Input: n = 1 Output: 1 Constraints: 0 <= n <= 109
Python/JS/Java/C++ sol by perfect square. [w/ Visualization]
1,200
bulb-switcher
0.481
brianchiang_tw
Medium
5,507
319
create maximum number
class Solution: def maxNumber(self, nums1: List[int], nums2: List[int], k: int) -> List[int]: def maximum_num_each_list(nums: List[int], k_i: int) -> List[int]: # monotonically decreasing stack s = [] m = len(nums) - k_i for n in nums: while s and s[-1] < n and m > 0: s.pop() m -= 1 s.append(n) s = s[:len(s)-m] # very important return s def greater(a, b, i , j): # get the number which is lexiographically greater while i< len(a) or j < len(b): if i == len(a): return False if j == len(b): return True if a[i] > b[j]: return True if a[i] < b[j]: return False i += 1 # we increment until each of their elements are same j += 1 def merge(x_num, y_num): n = len(x_num) m = len(y_num) i = 0 j = 0 s = [] while i < n or j < m: a = x_num[i] if i < n else float("-inf") b = y_num[j] if j < m else float("-inf") if a > b or greater(x_num, y_num, i , j): # greater(x_num, y_num, i , j): this function is meant for check which list has element lexicographically greater means it will iterate through both arrays incrementing both at the same time until one of them is greater than other. chosen = a i += 1 else: chosen = b j += 1 s.append(chosen) return s max_num_arr = [] for i in range(k+1): # we check for all values of k and find the maximum number we can create for that value of k and we repeat this for all values of k and then at eacch time merge the numbers to check if arrive at optimal solution first = maximum_num_each_list(nums1, i) second = maximum_num_each_list(nums2, k-i) merged = merge(first, second) # these two conditions are required because list comparison in python only compares the elements even if one of their lengths is greater, so I had to add these conditions to compare elements only if length is equal. # Alternatively you can avoid this and convert them both to int and then compare, but I wanted to this as it is somewhat more efficient. if len(merged) == len(max_num_arr) and merged > max_num_arr: max_num_arr = merged elif len(merged) > len(max_num_arr): max_num_arr = merged return max_num_arr
https://leetcode.com/problems/create-maximum-number/discuss/2167532/O(k(m%2Bn)).-Python-Solution-with-monotonically-decreasing-stack.-Commented-for-clarity.
2
You are given two integer arrays nums1 and nums2 of lengths m and n respectively. nums1 and nums2 represent the digits of two numbers. You are also given an integer k. Create the maximum number of length k <= m + n from digits of the two numbers. The relative order of the digits from the same array must be preserved. Return an array of the k digits representing the answer. Example 1: Input: nums1 = [3,4,6,5], nums2 = [9,1,2,5,8,3], k = 5 Output: [9,8,6,5,3] Example 2: Input: nums1 = [6,7], nums2 = [6,0,4], k = 5 Output: [6,7,6,0,4] Example 3: Input: nums1 = [3,9], nums2 = [8,9], k = 3 Output: [9,8,9] Constraints: m == nums1.length n == nums2.length 1 <= m, n <= 500 0 <= nums1[i], nums2[i] <= 9 1 <= k <= m + n
O(k(m+n)). Python Solution with monotonically decreasing stack. Commented for clarity.
443
create-maximum-number
0.288
saqibmubarak
Hard
5,514
321
coin change
class Solution: def coinChange(self, coins: List[int], amount: int) -> int: dp=[math.inf] * (amount+1) dp[0]=0 for coin in coins: for i in range(coin, amount+1): if i-coin>=0: dp[i]=min(dp[i], dp[i-coin]+1) return -1 if dp[-1]==math.inf else dp[-1]
https://leetcode.com/problems/coin-change/discuss/2058537/Python-Easy-2-DP-approaches
32
You are given an integer array coins representing coins of different denominations and an integer amount representing a total amount of money. Return the fewest number of coins that you need to make up that amount. If that amount of money cannot be made up by any combination of the coins, return -1. You may assume that you have an infinite number of each kind of coin. Example 1: Input: coins = [1,2,5], amount = 11 Output: 3 Explanation: 11 = 5 + 5 + 1 Example 2: Input: coins = [2], amount = 3 Output: -1 Example 3: Input: coins = [1], amount = 0 Output: 0 Constraints: 1 <= coins.length <= 12 1 <= coins[i] <= 231 - 1 0 <= amount <= 104
Python Easy 2 DP approaches
3,800
coin-change
0.416
constantine786
Medium
5,519
322
wiggle sort ii
class Solution: def wiggleSort(self, nums: List[int]) -> None: sortedList = sorted(nums) n = len(nums) if n%2==0: small = sortedList[:((n//2))][::-1] large = (sortedList[(n//2):])[::-1] for i in range(1,n,2): nums[i] = large[i//2] for i in range(0,n,2): nums[i] = small[i//2] else: small = sortedList[:1+((n//2))][::-1] large = (sortedList[1+(n//2):])[::-1] for i in range(1,n,2): nums[i] = large[i//2] for i in range(0,n,2): nums[i] = small[i//2]
https://leetcode.com/problems/wiggle-sort-ii/discuss/1322709/Definitely-not-O(n)-but-did-it-iteratively-in-O(nlog(N))-time
1
Given an integer array nums, reorder it such that nums[0] < nums[1] > nums[2] < nums[3].... You may assume the input array always has a valid answer. Example 1: Input: nums = [1,5,1,1,6,4] Output: [1,6,1,5,1,4] Explanation: [1,4,1,5,1,6] is also accepted. Example 2: Input: nums = [1,3,2,2,3,1] Output: [2,3,1,3,1,2] Constraints: 1 <= nums.length <= 5 * 104 0 <= nums[i] <= 5000 It is guaranteed that there will be an answer for the given input nums. Follow Up: Can you do it in O(n) time and/or in-place with O(1) extra space?
Definitely not O(n) but did it iteratively in O(nlog(N)) time
180
wiggle-sort-ii
0.33
prajwalPonnana004
Medium
5,579
324
power of three
class Solution: def isPowerOfThree(self, n: int) -> bool: if n == 1: return True if n == 0: return False else: return n % 3 == 0 and self.isPowerOfThree(n // 3)
https://leetcode.com/problems/power-of-three/discuss/1179790/Simple-Python-Recursive-Solution-with-Explanation
8
Given an integer n, return true if it is a power of three. Otherwise, return false. An integer n is a power of three, if there exists an integer x such that n == 3x. Example 1: Input: n = 27 Output: true Explanation: 27 = 33 Example 2: Input: n = 0 Output: false Explanation: There is no x where 3x = 0. Example 3: Input: n = -1 Output: false Explanation: There is no x where 3x = (-1). Constraints: -231 <= n <= 231 - 1 Follow up: Could you solve it without loops/recursion?
Simple Python Recursive Solution with Explanation
356
power-of-three
0.453
stevenbooke
Easy
5,582
326
count of range sum
class Solution: def countRangeSum(self, nums: List[int], lower: int, upper: int) -> int: prefix = [0] for x in nums: prefix.append(prefix[-1] + x) def fn(lo, hi): """Return count of range sum between prefix[lo:hi].""" if lo+1 >= hi: return 0 mid = lo + hi >> 1 ans = fn(lo, mid) + fn(mid, hi) k = kk = mid for i in range(lo, mid): while k < hi and prefix[k] - prefix[i] < lower: k += 1 while kk < hi and prefix[kk] - prefix[i] <= upper: kk += 1 ans += kk - k prefix[lo:hi] = sorted(prefix[lo:hi]) return ans return fn(0, len(prefix))
https://leetcode.com/problems/count-of-range-sum/discuss/1195369/Python3-4-solutions
8
Given an integer array nums and two integers lower and upper, return the number of range sums that lie in [lower, upper] inclusive. Range sum S(i, j) is defined as the sum of the elements in nums between indices i and j inclusive, where i <= j. Example 1: Input: nums = [-2,5,-1], lower = -2, upper = 2 Output: 3 Explanation: The three ranges are: [0,0], [2,2], and [0,2] and their respective sums are: -2, -1, 2. Example 2: Input: nums = [0], lower = 0, upper = 0 Output: 1 Constraints: 1 <= nums.length <= 105 -231 <= nums[i] <= 231 - 1 -105 <= lower <= upper <= 105 The answer is guaranteed to fit in a 32-bit integer.
[Python3] 4 solutions
459
count-of-range-sum
0.361
ye15
Hard
5,643
327
odd even linked list
class Solution: def oddEvenList(self, head: Optional[ListNode]) -> Optional[ListNode]: if(head is None or head.next is None): return head # assign odd = head(starting node of ODD) # assign even = head.next(starting node of EVEN) odd , even = head , head.next Even = even # keep starting point of Even Node so later we will connect with Odd Node while(odd.next and even.next): odd.next = odd.next.next # Connect odd.next to odd Node even.next = even.next.next # Connect even,next to Even Node odd = odd.next # move odd even = even.next # move even odd.next = Even # now connect odd.next to starting point to Even list return head
https://leetcode.com/problems/odd-even-linked-list/discuss/2458296/easy-approach-using-two-pointer-in-python-With-Comments-TC-%3A-O(N)-SC-%3A-O(1)
4
Given the head of a singly linked list, group all the nodes with odd indices together followed by the nodes with even indices, and return the reordered list. The first node is considered odd, and the second node is even, and so on. Note that the relative order inside both the even and odd groups should remain as it was in the input. You must solve the problem in O(1) extra space complexity and O(n) time complexity. Example 1: Input: head = [1,2,3,4,5] Output: [1,3,5,2,4] Example 2: Input: head = [2,1,3,5,6,4,7] Output: [2,3,6,7,1,5,4] Constraints: The number of nodes in the linked list is in the range [0, 104]. -106 <= Node.val <= 106
easy approach using two pointer in python With Comments [TC : O(N) SC : O(1)]
156
odd-even-linked-list
0.603
rajitkumarchauhan99
Medium
5,648
328
longest increasing path in a matrix
class Solution: def longestIncreasingPath(self, grid: List[List[int]]) -> int: m,n=len(grid),len(grid[0]) directions = [0, 1, 0, -1, 0] # four directions @lru_cache(maxsize=None) # using python cache lib for memoization def dfs(r,c): ans=1 # iterating through all 4 directions for i in range(4): new_row,new_col=r+directions[i], c+directions[i+1] # calculating the new cell # check if new cell is within the grid bounds and is an increasing sequence if 0<=new_row<m and 0<=new_col<n and grid[new_row][new_col]>grid[r][c]: ans = max(ans, dfs(new_row, new_col) + 1 ) # finding the max length of valid path from the current cell return ans return max(dfs(r,c) for r in range(m) for c in range(n))
https://leetcode.com/problems/longest-increasing-path-in-a-matrix/discuss/2052380/Python-DFS-with-Memoization-Beats-~90
4
Given an m x n integers matrix, return the length of the longest increasing path in matrix. From each cell, you can either move in four directions: left, right, up, or down. You may not move diagonally or move outside the boundary (i.e., wrap-around is not allowed). Example 1: Input: matrix = [[9,9,4],[6,6,8],[2,1,1]] Output: 4 Explanation: The longest increasing path is [1, 2, 6, 9]. Example 2: Input: matrix = [[3,4,5],[3,2,6],[2,2,1]] Output: 4 Explanation: The longest increasing path is [3, 4, 5, 6]. Moving diagonally is not allowed. Example 3: Input: matrix = [[1]] Output: 1 Constraints: m == matrix.length n == matrix[i].length 1 <= m, n <= 200 0 <= matrix[i][j] <= 231 - 1
Python DFS with Memoization Beats ~90%
580
longest-increasing-path-in-a-matrix
0.522
constantine786
Hard
5,669
329
patching array
class Solution: def minPatches(self, nums: List[int], n: int) -> int: ans, total = 0, 0 num_idx = 0 while total < n: if num_idx < len(nums): if total < nums[num_idx] - 1: total = total * 2 + 1 ans += 1 else: total += nums[num_idx] num_idx += 1 else: total = total * 2 + 1 ans += 1 return ans
https://leetcode.com/problems/patching-array/discuss/1432390/Python-3-easy-solution
1
Given a sorted integer array nums and an integer n, add/patch elements to the array such that any number in the range [1, n] inclusive can be formed by the sum of some elements in the array. Return the minimum number of patches required. Example 1: Input: nums = [1,3], n = 6 Output: 1 Explanation: Combinations of nums are [1], [3], [1,3], which form possible sums of: 1, 3, 4. Now if we add/patch 2 to nums, the combinations are: [1], [2], [3], [1,3], [2,3], [1,2,3]. Possible sums are 1, 2, 3, 4, 5, 6, which now covers the range [1, 6]. So we only need 1 patch. Example 2: Input: nums = [1,5,10], n = 20 Output: 2 Explanation: The two patches can be [2, 4]. Example 3: Input: nums = [1,2,2], n = 5 Output: 0 Constraints: 1 <= nums.length <= 1000 1 <= nums[i] <= 104 nums is sorted in ascending order. 1 <= n <= 231 - 1
Python 3 easy solution
231
patching-array
0.4
Andy_Feng97
Hard
5,714
330
verify preorder serialization of a binary tree
class Solution: def isValidSerialization(self, preorder: str) -> bool: stack = [] items = preorder.split(",") for i, val in enumerate(items): if i>0 and not stack: return False if stack: stack[-1][1] -= 1 if stack[-1][1] == 0: stack.pop() if val != "#": stack.append([val, 2]) return not stack
https://leetcode.com/problems/verify-preorder-serialization-of-a-binary-tree/discuss/1459342/Python3-or-O(n)-Time-and-O(n)-space
3
One way to serialize a binary tree is to use preorder traversal. When we encounter a non-null node, we record the node's value. If it is a null node, we record using a sentinel value such as '#'. For example, the above binary tree can be serialized to the string "9,3,4,#,#,1,#,#,2,#,6,#,#", where '#' represents a null node. Given a string of comma-separated values preorder, return true if it is a correct preorder traversal serialization of a binary tree. It is guaranteed that each comma-separated value in the string must be either an integer or a character '#' representing null pointer. You may assume that the input format is always valid. For example, it could never contain two consecutive commas, such as "1,,3". Note: You are not allowed to reconstruct the tree. Example 1: Input: preorder = "9,3,4,#,#,1,#,#,2,#,6,#,#" Output: true Example 2: Input: preorder = "1,#" Output: false Example 3: Input: preorder = "9,#,#,1" Output: false Constraints: 1 <= preorder.length <= 104 preorder consist of integers in the range [0, 100] and '#' separated by commas ','.
Python3 | O(n) Time and O(n) space
73
verify-preorder-serialization-of-a-binary-tree
0.443
Sanjaychandak95
Medium
5,716
331
reconstruct itinerary
class Solution: def __init__(self): self.path = [] def findItinerary(self, tickets: List[List[str]]) -> List[str]: flights = {} # as graph is directed # => no bi-directional paths for t1, t2 in tickets: if t1 not in flights: flights[t1] = [] flights[t1].append(t2) visited = {} for k, v in flights.items(): v.sort() visited[k] = [False for _ in range(len(v))] base_check = len(tickets) + 1 routes = ['JFK'] self.dfs('JFK', routes, base_check, flights, visited) return self.path def dfs(self, curr, routes, base_check, flights, visited): if len(routes) == base_check: self.path = routes return True # deadlock if curr not in flights: return False for idx in range(len(flights[curr])): if not visited[curr][idx]: visited[curr][idx] = True next_airport = flights[curr][idx] routes += [next_airport] result = self.dfs(next_airport, routes, base_check, flights, visited) if result: return True routes.pop() visited[curr][idx] = False return False
https://leetcode.com/problems/reconstruct-itinerary/discuss/1475876/Python-LC-but-better-explained
1
You are given a list of airline tickets where tickets[i] = [fromi, toi] represent the departure and the arrival airports of one flight. Reconstruct the itinerary in order and return it. All of the tickets belong to a man who departs from "JFK", thus, the itinerary must begin with "JFK". If there are multiple valid itineraries, you should return the itinerary that has the smallest lexical order when read as a single string. For example, the itinerary ["JFK", "LGA"] has a smaller lexical order than ["JFK", "LGB"]. You may assume all tickets form at least one valid itinerary. You must use all the tickets once and only once. Example 1: Input: tickets = [["MUC","LHR"],["JFK","MUC"],["SFO","SJC"],["LHR","SFO"]] Output: ["JFK","MUC","LHR","SFO","SJC"] Example 2: Input: tickets = [["JFK","SFO"],["JFK","ATL"],["SFO","ATL"],["ATL","JFK"],["ATL","SFO"]] Output: ["JFK","ATL","JFK","SFO","ATL","SFO"] Explanation: Another possible reconstruction is ["JFK","SFO","ATL","JFK","ATL","SFO"] but it is larger in lexical order. Constraints: 1 <= tickets.length <= 300 tickets[i].length == 2 fromi.length == 3 toi.length == 3 fromi and toi consist of uppercase English letters. fromi != toi
Python LC, but better explained
213
reconstruct-itinerary
0.41
SleeplessChallenger
Hard
5,724
332
increasing triplet subsequence
class Solution: def increasingTriplet(self, nums: List[int]) -> bool: n = len(nums) maxRight = [0] * n # maxRight[i] is the maximum element among nums[i+1...n-1] maxRight[-1] = nums[-1] for i in range(n-2, -1, -1): maxRight[i] = max(maxRight[i+1], nums[i+1]) minLeft = nums[0] for i in range(1, n-1): if minLeft < nums[i] < maxRight[i]: return True minLeft = min(minLeft, nums[i]) return False
https://leetcode.com/problems/increasing-triplet-subsequence/discuss/270884/Python-2-solutions%3A-Right-So-Far-One-pass-O(1)-Space-Clean-and-Concise
94
Given an integer array nums, return true if there exists a triple of indices (i, j, k) such that i < j < k and nums[i] < nums[j] < nums[k]. If no such indices exists, return false. Example 1: Input: nums = [1,2,3,4,5] Output: true Explanation: Any triplet where i < j < k is valid. Example 2: Input: nums = [5,4,3,2,1] Output: false Explanation: No triplet exists. Example 3: Input: nums = [2,1,5,0,4,6] Output: true Explanation: The triplet (3, 4, 5) is valid because nums[3] == 0 < nums[4] == 4 < nums[5] == 6. Constraints: 1 <= nums.length <= 5 * 105 -231 <= nums[i] <= 231 - 1 Follow up: Could you implement a solution that runs in O(n) time complexity and O(1) space complexity?
[Python] 2 solutions: Right So Far, One pass - O(1) Space - Clean & Concise
2,000
increasing-triplet-subsequence
0.427
hiepit
Medium
5,735
334
self crossing
class Solution: def isSelfCrossing(self, x: List[int]) -> bool: def intersect(p1, p2, p3, p4): v1 = p2 - p1 if v1.real == 0: return p1.imag <= p3.imag <= p2.imag and p3.real <= p1.real <= p4.real return p3.imag <= p1.imag <= p4.imag and p1.real <= p3.real <= p2.real def overlap(p1, p2, p3, p4): v1 = p2 - p1 if v1.real == 0: return min(p2.imag, p4.imag) >= max(p1.imag, p3.imag) and p1.real == p3.real return min(p2.real, p4.real) >= max(p1.real, p3.real) and p1.imag == p3.imag uv = complex(0, 1) p = complex(0, 0) segments = deque() for s in x: segments.append(sorted([p, (np := p + uv * s)], key=lambda x:(x.real, x.imag))) if len(segments) > 5 and intersect(*segments[-1], *segments[-6]): return True if len(segments) > 4 and overlap(*segments[-1], *segments[-5]): return True if len(segments) > 3 and intersect(*segments[-1], *segments[-4]): return True if len(segments) == 6: segments.popleft() p = np uv *= complex(0, 1) return False
https://leetcode.com/problems/self-crossing/discuss/710582/Python3-complex-number-solution-Self-Crossing
0
You are given an array of integers distance. You start at the point (0, 0) on an X-Y plane, and you move distance[0] meters to the north, then distance[1] meters to the west, distance[2] meters to the south, distance[3] meters to the east, and so on. In other words, after each move, your direction changes counter-clockwise. Return true if your path crosses itself or false if it does not. Example 1: Input: distance = [2,1,1,2] Output: true Explanation: The path crosses itself at the point (0, 1). Example 2: Input: distance = [1,2,3,4] Output: false Explanation: The path does not cross itself at any point. Example 3: Input: distance = [1,1,1,2,1] Output: true Explanation: The path crosses itself at the point (0, 0). Constraints: 1 <= distance.length <= 105 1 <= distance[i] <= 105
Python3 complex number solution - Self Crossing
221
self-crossing
0.293
r0bertz
Hard
5,790
335
palindrome pairs
class Solution: def palindromePairs(self, words: List[str]) -> List[List[int]]: backward, res = {}, [] for i, word in enumerate(words): backward[word[::-1]] = i for i, word in enumerate(words): if word in backward and backward[word] != i: res.append([i, backward[word]]) if word != "" and "" in backward and word == word[::-1]: res.append([i, backward[""]]) res.append([backward[""], i]) for j in range(len(word)): if word[j:] in backward and word[:j] == word[j-1::-1]: res.append([backward[word[j:]], i]) if word[:j] in backward and word[j:] == word[:j-1:-1]: res.append([i, backward[word[:j]]]) return res
https://leetcode.com/problems/palindrome-pairs/discuss/2585442/Intuitive-Python3-or-HashMap-or-95-Time-and-Space-or-O(N*W2)
54
You are given a 0-indexed array of unique strings words. A palindrome pair is a pair of integers (i, j) such that: 0 <= i, j < words.length, i != j, and words[i] + words[j] (the concatenation of the two strings) is a palindrome . Return an array of all the palindrome pairs of words. You must write an algorithm with O(sum of words[i].length) runtime complexity. Example 1: Input: words = ["abcd","dcba","lls","s","sssll"] Output: [[0,1],[1,0],[3,2],[2,4]] Explanation: The palindromes are ["abcddcba","dcbaabcd","slls","llssssll"] Example 2: Input: words = ["bat","tab","cat"] Output: [[0,1],[1,0]] Explanation: The palindromes are ["battab","tabbat"] Example 3: Input: words = ["a",""] Output: [[0,1],[1,0]] Explanation: The palindromes are ["a","a"] Constraints: 1 <= words.length <= 5000 0 <= words[i].length <= 300 words[i] consists of lowercase English letters.
Intuitive Python3 | HashMap | 95% Time & Space | O(N*W^2)
3,000
palindrome-pairs
0.352
ryangrayson
Hard
5,791
336
house robber iii
class Solution: def rob(self, root: TreeNode) -> int: def dfs(node): if not node: return 0, 0 left, right = dfs(node.left), dfs(node.right) v_take = node.val + left[1] + right[1] v_not_take = max(left) + max(right) return v_take, v_not_take return max(dfs(root))
https://leetcode.com/problems/house-robber-iii/discuss/872676/Python-3-or-DFS-Backtracking-or-Explanation
5
The thief has found himself a new place for his thievery again. There is only one entrance to this area, called root. Besides the root, each house has one and only one parent house. After a tour, the smart thief realized that all houses in this place form a binary tree. It will automatically contact the police if two directly-linked houses were broken into on the same night. Given the root of the binary tree, return the maximum amount of money the thief can rob without alerting the police. Example 1: Input: root = [3,2,3,null,3,null,1] Output: 7 Explanation: Maximum amount of money the thief can rob = 3 + 3 + 1 = 7. Example 2: Input: root = [3,4,5,1,3,null,1] Output: 9 Explanation: Maximum amount of money the thief can rob = 4 + 5 = 9. Constraints: The number of nodes in the tree is in the range [1, 104]. 0 <= Node.val <= 104
Python 3 | DFS, Backtracking | Explanation
439
house-robber-iii
0.539
idontknoooo
Medium
5,801
337
counting bits
class Solution: def countBits(self, N: int) -> List[int]: stem = [0] while len(stem) < N+1: stem.extend([s + 1 for s in stem]) return stem[:N+1]
https://leetcode.com/problems/counting-bits/discuss/466438/Python-clean-no-cheat-easy-to-understand.-Based-on-pattern.-Beats-90.
18
Given an integer n, return an array ans of length n + 1 such that for each i (0 <= i <= n), ans[i] is the number of 1's in the binary representation of i. Example 1: Input: n = 2 Output: [0,1,1] Explanation: 0 --> 0 1 --> 1 2 --> 10 Example 2: Input: n = 5 Output: [0,1,1,2,1,2] Explanation: 0 --> 0 1 --> 1 2 --> 10 3 --> 11 4 --> 100 5 --> 101 Constraints: 0 <= n <= 105 Follow up: It is very easy to come up with a solution with a runtime of O(n log n). Can you do it in linear time O(n) and possibly in a single pass? Can you do it without using any built-in function (i.e., like __builtin_popcount in C++)?
Python clean, no cheat, easy to understand. Based on pattern. Beats 90%.
1,100
counting-bits
0.753
kimonode
Easy
5,817
338
power of four
class Solution: def isPowerOfFour(self, num: int) -> bool: return num > 0 and not num &amp; (num - 1) and len(bin(num)) % 2
https://leetcode.com/problems/power-of-four/discuss/772261/Python3-1-liner-99.95-O(1)-explained
9
Given an integer n, return true if it is a power of four. Otherwise, return false. An integer n is a power of four, if there exists an integer x such that n == 4x. Example 1: Input: n = 16 Output: true Example 2: Input: n = 5 Output: false Example 3: Input: n = 1 Output: true Constraints: -231 <= n <= 231 - 1 Follow up: Could you solve it without loops/recursion?
Python3 1 liner 99.95% O(1), explained
546
power-of-four
0.458
dangtrangiabao
Easy
5,879
342
integer break
class Solution: def integerBreak(self, n: int) -> int: if(n<=3): return n-1 n3=n//3 r3=n%3 if(r3==0): return 3**n3 if(r3==1): r3=4 n3-=1 return r3*(3**n3)
https://leetcode.com/problems/integer-break/discuss/2830343/O(1)-oror-TC1-10-line-code
7
Given an integer n, break it into the sum of k positive integers, where k >= 2, and maximize the product of those integers. Return the maximum product you can get. Example 1: Input: n = 2 Output: 1 Explanation: 2 = 1 + 1, 1 × 1 = 1. Example 2: Input: n = 10 Output: 36 Explanation: 10 = 3 + 3 + 4, 3 × 3 × 4 = 36. Constraints: 2 <= n <= 58
O(1) || TC=1 10 line code
71
integer-break
0.554
droj
Medium
5,926
343
reverse string
class Solution: def reverseString(self, s: List[str]) -> None: s[:] = s[::-1]
https://leetcode.com/problems/reverse-string/discuss/670137/Python-3-~actually~-easiest-solution
77
Write a function that reverses a string. The input string is given as an array of characters s. You must do this by modifying the input array in-place with O(1) extra memory. Example 1: Input: s = ["h","e","l","l","o"] Output: ["o","l","l","e","h"] Example 2: Input: s = ["H","a","n","n","a","h"] Output: ["h","a","n","n","a","H"] Constraints: 1 <= s.length <= 105 s[i] is a printable ascii character.
Python 3 ~actually~ easiest solution
6,800
reverse-string
0.762
drblessing
Easy
5,954
344
reverse vowels of a string
class Solution: def reverseVowels(self, s: str) -> str: s = list(s) left = 0 right = len(s) - 1 m = 'aeiouAEIOU' while left < right: if s[left] in m and s[right] in m: s[left], s[right] = s[right], s[left] left += 1; right -= 1 elif s[left] not in m: left += 1 elif s[right] not in m: right -= 1 return ''.join(s)
https://leetcode.com/problems/reverse-vowels-of-a-string/discuss/1164745/Python-Solution-oror-99.58-faster-oror-86.96-less-memory
22
Given a string s, reverse only all the vowels in the string and return it. The vowels are 'a', 'e', 'i', 'o', and 'u', and they can appear in both lower and upper cases, more than once. Example 1: Input: s = "hello" Output: "holle" Example 2: Input: s = "leetcode" Output: "leotcede" Constraints: 1 <= s.length <= 3 * 105 s consist of printable ASCII characters.
Python Solution || 99.58% faster || 86.96% less memory
1,100
reverse-vowels-of-a-string
0.498
KiranUpase
Easy
6,016
345
top k frequent elements
class Solution: def topKFrequent(self, nums: List[int], k: int) -> List[int]: frequency = {} for num in nums: if num not in frequency: frequency[num] = 1 else: frequency[num] = frequency[num] + 1 frequency = dict(sorted(frequency.items(), key=lambda x: x[1], reverse=True)) result = list(frequency.keys())[:k] return result
https://leetcode.com/problems/top-k-frequent-elements/discuss/1928198/Python-Simple-Python-Solution-Using-Dictionary-(-HashMap-)
24
Given an integer array nums and an integer k, return the k most frequent elements. You may return the answer in any order. Example 1: Input: nums = [1,1,1,2,2,3], k = 2 Output: [1,2] Example 2: Input: nums = [1], k = 1 Output: [1] Constraints: 1 <= nums.length <= 105 -104 <= nums[i] <= 104 k is in the range [1, the number of unique elements in the array]. It is guaranteed that the answer is unique. Follow up: Your algorithm's time complexity must be better than O(n log n), where n is the array's size.
[ Python ] ✅✅ Simple Python Solution Using Dictionary ( HashMap ) ✌👍
2,800
top-k-frequent-elements
0.648
ASHOK_KUMAR_MEGHVANSHI
Medium
6,072
347
intersection of two arrays
class Solution: def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]: a = [] for i in nums1: if i not in a and i in nums2: a.append(i) return a
https://leetcode.com/problems/intersection-of-two-arrays/discuss/2270388/PYTHON-3-SIMPLE-or-EASY-TO-UNDERSTAND
5
Given two integer arrays nums1 and nums2, return an array of their intersection . Each element in the result must be unique and you may return the result in any order. Example 1: Input: nums1 = [1,2,2,1], nums2 = [2,2] Output: [2] Example 2: Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4] Output: [9,4] Explanation: [4,9] is also accepted. Constraints: 1 <= nums1.length, nums2.length <= 1000 0 <= nums1[i], nums2[i] <= 1000
[PYTHON 3] SIMPLE | EASY TO UNDERSTAND
135
intersection-of-two-arrays
0.704
omkarxpatel
Easy
6,131
349
intersection of two arrays ii
class Solution: def intersect(self, nums1: List[int], nums2: List[int]) -> List[int]: nums1.sort() nums2.sort() one=0 two=0 ans=[] while one < len(nums1) and two < len(nums2): if nums1[one] < nums2[two]: one+=1 elif nums2[two] < nums1[one]: two+=1 else: ans.append(nums1[one]) one+=1 two+=1 return ans
https://leetcode.com/problems/intersection-of-two-arrays-ii/discuss/1231807/easy-or-two-pointer-method-or-python
23
Given two integer arrays nums1 and nums2, return an array of their intersection. Each element in the result must appear as many times as it shows in both arrays and you may return the result in any order. Example 1: Input: nums1 = [1,2,2,1], nums2 = [2,2] Output: [2,2] Example 2: Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4] Output: [4,9] Explanation: [9,4] is also accepted. Constraints: 1 <= nums1.length, nums2.length <= 1000 0 <= nums1[i], nums2[i] <= 1000 Follow up: What if the given array is already sorted? How would you optimize your algorithm? What if nums1's size is small compared to nums2's size? Which algorithm is better? What if elements of nums2 are stored on disk, and the memory is limited such that you cannot load all elements into the memory at once?
easy | two pointer method | python
1,300
intersection-of-two-arrays-ii
0.556
chikushen99
Easy
6,183
350
russian doll envelopes
class Solution: def maxEnvelopes(self, envelopes: List[List[int]]) -> int: envelopes.sort(key=lambda x: (x[0], -x[1])) res = [] # Perform LIS for _, h in envelopes: l,r=0,len(res)-1 # find the insertion point in the Sort order while l <= r: mid=(l+r)>>1 if res[mid]>=h: r=mid-1 else: l=mid+1 idx = l if idx == len(res): res.append(h) else: res[idx]=h return len(res)
https://leetcode.com/problems/russian-doll-envelopes/discuss/2071626/Python-LIS-based-approach
19
You are given a 2D array of integers envelopes where envelopes[i] = [wi, hi] represents the width and the height of an envelope. One envelope can fit into another if and only if both the width and height of one envelope are greater than the other envelope's width and height. Return the maximum number of envelopes you can Russian doll (i.e., put one inside the other). Note: You cannot rotate an envelope. Example 1: Input: envelopes = [[5,4],[6,4],[6,7],[2,3]] Output: 3 Explanation: The maximum number of envelopes you can Russian doll is 3 ([2,3] => [5,4] => [6,7]). Example 2: Input: envelopes = [[1,1],[1,1],[1,1]] Output: 1 Constraints: 1 <= envelopes.length <= 105 envelopes[i].length == 2 1 <= wi, hi <= 105
Python LIS based approach
1,800
russian-doll-envelopes
0.382
constantine786
Hard
6,234
354
count numbers with unique digits
class Solution: def countNumbersWithUniqueDigits(self, n: int) -> int: if n == 0: return 1 if n == 1: return 10 res = 91 mult = 8 comb = 81 for i in range(n - 2): comb *= mult mult -= 1 res += comb return res
https://leetcode.com/problems/count-numbers-with-unique-digits/discuss/2828071/Python3-Mathematics-approach.-Explained-in-details.-Step-by-step
0
Given an integer n, return the count of all numbers with unique digits, x, where 0 <= x < 10n. Example 1: Input: n = 2 Output: 91 Explanation: The answer should be the total numbers in the range of 0 ≤ x < 100, excluding 11,22,33,44,55,66,77,88,99 Example 2: Input: n = 0 Output: 1 Constraints: 0 <= n <= 8
Python3 Mathematics approach. Explained in details. Step-by-step
2
count-numbers-with-unique-digits
0.516
Alex_Gr
Medium
6,239
357
max sum of rectangle no larger than k
class Solution: def maxSumSubmatrix(self, matrix: List[List[int]], k: int) -> int: ans = float("-inf") m, n = len(matrix), len(matrix[0]) for i in range(n): lstSum = [0] * m for j in range(i, n): currSum = 0 curlstSum = [0] for t in range(m): lstSum[t] += matrix[t][j] currSum += lstSum[t] pos = bisect_left(curlstSum, currSum - k) if pos < len(curlstSum): if curlstSum[pos] == currSum - k: return k else: ans = max(ans, currSum - curlstSum[pos]) insort(curlstSum, currSum) return ans
https://leetcode.com/problems/max-sum-of-rectangle-no-larger-than-k/discuss/2488882/Solution-In-Python
8
Given an m x n matrix matrix and an integer k, return the max sum of a rectangle in the matrix such that its sum is no larger than k. It is guaranteed that there will be a rectangle with a sum no larger than k. Example 1: Input: matrix = [[1,0,1],[0,-2,3]], k = 2 Output: 2 Explanation: Because the sum of the blue rectangle [[0, 1], [-2, 3]] is 2, and 2 is the max number no larger than k (k = 2). Example 2: Input: matrix = [[2,2,-1]], k = 3 Output: 3 Constraints: m == matrix.length n == matrix[i].length 1 <= m, n <= 100 -100 <= matrix[i][j] <= 100 -105 <= k <= 105 Follow up: What if the number of rows is much larger than the number of columns?
Solution In Python
1,200
max-sum-of-rectangle-no-larger-than-k
0.441
AY_
Hard
6,250
363
water and jug problem
class Solution: def canMeasureWater(self, x: int, y: int, z: int) -> bool: return False if x + y < z else True if x + y == 0 else not z % math.gcd(x,y) - Junaid Mansuri (LeetCode ID)@hotmail.com
https://leetcode.com/problems/water-and-jug-problem/discuss/393886/Solution-in-Python-3-(beats-~100)-(one-line)-(Math-Solution)
5
You are given two jugs with capacities x liters and y liters. You have an infinite water supply. Return whether the total amount of water in both jugs may reach target using the following operations: Fill either jug completely with water. Completely empty either jug. Pour water from one jug into another until the receiving jug is full, or the transferring jug is empty. Example 1: Input: x = 3, y = 5, target = 4 Output: true Explanation: Follow these steps to reach a total of 4 liters: Fill the 5-liter jug (0, 5). Pour from the 5-liter jug into the 3-liter jug, leaving 2 liters (3, 2). Empty the 3-liter jug (0, 2). Transfer the 2 liters from the 5-liter jug to the 3-liter jug (2, 0). Fill the 5-liter jug again (2, 5). Pour from the 5-liter jug into the 3-liter jug until the 3-liter jug is full. This leaves 4 liters in the 5-liter jug (3, 4). Empty the 3-liter jug. Now, you have exactly 4 liters in the 5-liter jug (0, 4). Reference: The Die Hard example. Example 2: Input: x = 2, y = 6, target = 5 Output: false Example 3: Input: x = 1, y = 2, target = 3 Output: true Explanation: Fill both jugs. The total amount of water in both jugs is equal to 3 now. Constraints: 1 <= x, y, target <= 103
Solution in Python 3 (beats ~100%) (one line) (Math Solution)
1,300
water-and-jug-problem
0.367
junaidmansuri
Medium
6,254
365
valid perfect square
class Solution: def isPerfectSquare(self, num: int) -> bool: return int(num**0.5) == num**0.5
https://leetcode.com/problems/valid-perfect-square/discuss/1063963/100-Python-One-Liner-UPVOTE-PLEASE
6
Given a positive integer num, return true if num is a perfect square or false otherwise. A perfect square is an integer that is the square of an integer. In other words, it is the product of some integer with itself. You must not use any built-in library function, such as sqrt. Example 1: Input: num = 16 Output: true Explanation: We return true because 4 * 4 = 16 and 4 is an integer. Example 2: Input: num = 14 Output: false Explanation: We return false because 3.742 * 3.742 = 14 and 3.742 is not an integer. Constraints: 1 <= num <= 231 - 1
100% Python One-Liner UPVOTE PLEASE
451
valid-perfect-square
0.433
1coder
Easy
6,265
367
largest divisible subset
class Solution: def largestDivisibleSubset(self, nums: List[int]) -> List[int]: if not nums or len(nums) == 0: return [] # since we are doing a "subset" question # sorting does not make any differences nums.sort() n = len(nums) # initilization # f[i] represents the size of LDS ended with nums[i] f = [1 for _ in range(n)] for i in range(1, n): for j in range(i): # since we have already sorted, # then nums[j] % nums[i] will never equals zero # unless nums[i] == nums[j] if nums[i] % nums[j] == 0: f[i] = max(f[i], f[j] + 1) # extract result from dp array max_size = max(f) max_idx = f.index(max_size) # since we can return one of the largest prev_num, prev_size = nums[max_idx], f[max_idx] res = [prev_num] for curr_idx in range(max_idx, -1, -1): if prev_num % nums[curr_idx] == 0 and f[curr_idx] == prev_size - 1: # update res.append(nums[curr_idx]) prev_num = nums[curr_idx] prev_size = f[curr_idx] return res[::-1]
https://leetcode.com/problems/largest-divisible-subset/discuss/1127633/Python-Dynamic-Programming-with-comments
3
Given a set of distinct positive integers nums, return the largest subset answer such that every pair (answer[i], answer[j]) of elements in this subset satisfies: answer[i] % answer[j] == 0, or answer[j] % answer[i] == 0 If there are multiple solutions, return any of them. Example 1: Input: nums = [1,2,3] Output: [1,2] Explanation: [1,3] is also accepted. Example 2: Input: nums = [1,2,4,8] Output: [1,2,4,8] Constraints: 1 <= nums.length <= 1000 1 <= nums[i] <= 2 * 109 All the integers in nums are unique.
Python Dynamic Programming with comments
227
largest-divisible-subset
0.413
zna2
Medium
6,316
368
sum of two integers
class Solution: def getSum(self, a: int, b: int) -> int: return int(math.log2(2**a * 2**b))
https://leetcode.com/problems/sum-of-two-integers/discuss/1876632/Python-one-line-solution-using-the-logic-of-logs-and-powers
7
Given two integers a and b, return the sum of the two integers without using the operators + and -. Example 1: Input: a = 1, b = 2 Output: 3 Example 2: Input: a = 2, b = 3 Output: 5 Constraints: -1000 <= a, b <= 1000
Python one line solution using the logic of logs and powers
596
sum-of-two-integers
0.507
alishak1999
Medium
6,324
371
super pow
class Solution: def superPow(self, a: int, b: List[int]) -> int: return (a % 1337)**(1140 + int(''.join(map(str, b))) % 1140) % 1337 - Junaid Mansuri
https://leetcode.com/problems/super-pow/discuss/400893/Python-3-(With-Explanation)-(Handles-All-Test-Cases)-(one-line)-(beats-~97)
11
Your task is to calculate ab mod 1337 where a is a positive integer and b is an extremely large positive integer given in the form of an array. Example 1: Input: a = 2, b = [3] Output: 8 Example 2: Input: a = 2, b = [1,0] Output: 1024 Example 3: Input: a = 1, b = [4,3,3,8,5,2] Output: 1 Constraints: 1 <= a <= 231 - 1 1 <= b.length <= 2000 0 <= b[i] <= 9 b does not contain leading zeros.
Python 3 (With Explanation) (Handles All Test Cases) (one line) (beats ~97%)
1,900
super-pow
0.371
junaidmansuri
Medium
6,343
372
find k pairs with smallest sums
class Solution: def kSmallestPairs(self, nums1: List[int], nums2: List[int], k: int) -> List[List[int]]: hq = [] heapq.heapify(hq) # add all the pairs that we can form with # all the (first k) items in nums1 with the first # item in nums2 for i in range(min(len(nums1), k)): heapq.heappush(hq, (nums1[i]+nums2[0], nums1[i], nums2[0], 0)) # since the smallest pair will # be the first element from both nums1 and nums2. We'll # start with that and then subsequently, we'll pop it out # from the heap and also insert the pair of the current # element from nums1 with the next nums2 element out = [] while k > 0 and hq: _, n1, n2, idx = heapq.heappop(hq) out.append((n1, n2)) if idx + 1 < len(nums2): # the heap will ensure that the smallest element # based on the sum will remain on top and the # next iteration will give us the pair we require heapq.heappush(hq, (n1+nums2[idx+1], n1, nums2[idx+1], idx+1)) k -= 1 return out
https://leetcode.com/problems/find-k-pairs-with-smallest-sums/discuss/1701122/Python-Simple-heap-solution-explained
11
You are given two integer arrays nums1 and nums2 sorted in non-decreasing order and an integer k. Define a pair (u, v) which consists of one element from the first array and one element from the second array. Return the k pairs (u1, v1), (u2, v2), ..., (uk, vk) with the smallest sums. Example 1: Input: nums1 = [1,7,11], nums2 = [2,4,6], k = 3 Output: [[1,2],[1,4],[1,6]] Explanation: The first 3 pairs are returned from the sequence: [1,2],[1,4],[1,6],[7,2],[7,4],[11,2],[7,6],[11,4],[11,6] Example 2: Input: nums1 = [1,1,2], nums2 = [1,2,3], k = 2 Output: [[1,1],[1,1]] Explanation: The first 2 pairs are returned from the sequence: [1,1],[1,1],[1,2],[2,1],[1,2],[2,2],[1,3],[1,3],[2,3] Constraints: 1 <= nums1.length, nums2.length <= 105 -109 <= nums1[i], nums2[i] <= 109 nums1 and nums2 both are sorted in non-decreasing order. 1 <= k <= 104 k <= nums1.length * nums2.length
[Python] Simple heap solution explained
1,400
find-k-pairs-with-smallest-sums
0.383
buccatini
Medium
6,363
373
guess number higher or lower
class Solution: def guessNumber(self, n: int) -> int: return __pick__
https://leetcode.com/problems/guess-number-higher-or-lower/discuss/2717871/DONT-TRY-THIS-CODE-or-ONE-LINE-PYTHON-CODE
9
We are playing the Guess Game. The game is as follows: I pick a number from 1 to n. You have to guess which number I picked. Every time you guess wrong, I will tell you whether the number I picked is higher or lower than your guess. You call a pre-defined API int guess(int num), which returns three possible results: -1: Your guess is higher than the number I picked (i.e. num > pick). 1: Your guess is lower than the number I picked (i.e. num < pick). 0: your guess is equal to the number I picked (i.e. num == pick). Return the number that I picked. Example 1: Input: n = 10, pick = 6 Output: 6 Example 2: Input: n = 1, pick = 1 Output: 1 Example 3: Input: n = 2, pick = 1 Output: 1 Constraints: 1 <= n <= 231 - 1 1 <= pick <= n
DONT TRY THIS CODE | ONE LINE PYTHON CODE
441
guess-number-higher-or-lower
0.514
raghavdabra
Easy
6,377
374
guess number higher or lower ii
class Solution: def getMoneyAmount(self, n: int) -> int: if n == 1: return 1 starting_index = 1 if n % 2 == 0 else 2 selected_nums = [i for i in range(starting_index, n, 2)] selected_nums_length = len(selected_nums) dp = [[0] * selected_nums_length for _ in range(selected_nums_length)] for i in range(selected_nums_length): dp[i][i] = selected_nums[i] for length in range(2, selected_nums_length + 1): for i in range(selected_nums_length - length + 1): j = i + length - 1 dp[i][j] = float("inf") for k in range(i, j + 1): dp_left = dp[i][k - 1] if k != 0 else 0 dp_right = dp[k + 1][j] if k != j else 0 dp[i][j] = min(dp[i][j], selected_nums[k] + max(dp_left, dp_right)) return dp[0][-1]
https://leetcode.com/problems/guess-number-higher-or-lower-ii/discuss/1510747/Python-DP-beat-97.52-in-time-99-in-memory-(with-explanation)
31
We are playing the Guessing Game. The game will work as follows: I pick a number between 1 and n. You guess a number. If you guess the right number, you win the game. If you guess the wrong number, then I will tell you whether the number I picked is higher or lower, and you will continue guessing. Every time you guess a wrong number x, you will pay x dollars. If you run out of money, you lose the game. Given a particular n, return the minimum amount of money you need to guarantee a win regardless of what number I pick. Example 1: Input: n = 10 Output: 16 Explanation: The winning strategy is as follows: - The range is [1,10]. Guess 7. - If this is my number, your total is $0. Otherwise, you pay $7. - If my number is higher, the range is [8,10]. Guess 9. - If this is my number, your total is $7. Otherwise, you pay $9. - If my number is higher, it must be 10. Guess 10. Your total is $7 + $9 = $16. - If my number is lower, it must be 8. Guess 8. Your total is $7 + $9 = $16. - If my number is lower, the range is [1,6]. Guess 3. - If this is my number, your total is $7. Otherwise, you pay $3. - If my number is higher, the range is [4,6]. Guess 5. - If this is my number, your total is $7 + $3 = $10. Otherwise, you pay $5. - If my number is higher, it must be 6. Guess 6. Your total is $7 + $3 + $5 = $15. - If my number is lower, it must be 4. Guess 4. Your total is $7 + $3 + $5 = $15. - If my number is lower, the range is [1,2]. Guess 1. - If this is my number, your total is $7 + $3 = $10. Otherwise, you pay $1. - If my number is higher, it must be 2. Guess 2. Your total is $7 + $3 + $1 = $11. The worst case in all these scenarios is that you pay $16. Hence, you only need $16 to guarantee a win. Example 2: Input: n = 1 Output: 0 Explanation: There is only one possible number, so you can guess 1 and not have to pay anything. Example 3: Input: n = 2 Output: 1 Explanation: There are two possible numbers, 1 and 2. - Guess 1. - If this is my number, your total is $0. Otherwise, you pay $1. - If my number is higher, it must be 2. Guess 2. Your total is $1. The worst case is that you pay $1. Constraints: 1 <= n <= 200
[Python] DP, beat 97.52% in time, 99% in memory (with explanation)
1,100
guess-number-higher-or-lower-ii
0.465
wingskh
Medium
6,399
375
wiggle subsequence
class Solution: def wiggleMaxLength(self, nums: List[int]) -> int: length = 0 curr = 0 for i in range(len(nums) - 1): if curr == 0 and nums[i + 1] - nums[i] != 0: length += 1 curr = nums[i + 1] - nums[i] if curr < 0 and nums[i + 1] - nums[i] > 0: length += 1 curr = nums[i + 1] - nums[i] elif curr > 0 and nums[i + 1] - nums[i] < 0: length += 1 curr = nums[i + 1] - nums[i] else: continue return length + 1
https://leetcode.com/problems/wiggle-subsequence/discuss/2230152/Beats-73.3-Simple-Python-Solution-Greedy
3
A wiggle sequence is a sequence where the differences between successive numbers strictly alternate between positive and negative. The first difference (if one exists) may be either positive or negative. A sequence with one element and a sequence with two non-equal elements are trivially wiggle sequences. For example, [1, 7, 4, 9, 2, 5] is a wiggle sequence because the differences (6, -3, 5, -7, 3) alternate between positive and negative. In contrast, [1, 4, 7, 2, 5] and [1, 7, 4, 5, 5] are not wiggle sequences. The first is not because its first two differences are positive, and the second is not because its last difference is zero. A subsequence is obtained by deleting some elements (possibly zero) from the original sequence, leaving the remaining elements in their original order. Given an integer array nums, return the length of the longest wiggle subsequence of nums. Example 1: Input: nums = [1,7,4,9,2,5] Output: 6 Explanation: The entire sequence is a wiggle sequence with differences (6, -3, 5, -7, 3). Example 2: Input: nums = [1,17,5,10,13,15,10,5,16,8] Output: 7 Explanation: There are several subsequences that achieve this length. One is [1, 17, 10, 13, 10, 16, 8] with differences (16, -7, 3, -3, 6, -8). Example 3: Input: nums = [1,2,3,4,5,6,7,8,9] Output: 2 Constraints: 1 <= nums.length <= 1000 0 <= nums[i] <= 1000 Follow up: Could you solve this in O(n) time?
Beats 73.3% - Simple Python Solution - Greedy
183
wiggle-subsequence
0.482
7yler
Medium
6,406
376
combination sum iv
class Solution: def combinationSum4(self, nums: List[int], target: int) -> int: waysToAdd = [0 for x in range(target+1)] waysToAdd[0] = 1 for i in range(min(nums), target+1): waysToAdd[i] = sum(waysToAdd[i-num] for num in nums if i-num >= 0) return waysToAdd[-1]
https://leetcode.com/problems/combination-sum-iv/discuss/1272869/Python-3-Faster-than-96-(Super-Simple!)
3
Given an array of distinct integers nums and a target integer target, return the number of possible combinations that add up to target. The test cases are generated so that the answer can fit in a 32-bit integer. Example 1: Input: nums = [1,2,3], target = 4 Output: 7 Explanation: The possible combination ways are: (1, 1, 1, 1) (1, 1, 2) (1, 2, 1) (1, 3) (2, 1, 1) (2, 2) (3, 1) Note that different sequences are counted as different combinations. Example 2: Input: nums = [9], target = 3 Output: 0 Constraints: 1 <= nums.length <= 200 1 <= nums[i] <= 1000 All the elements of nums are unique. 1 <= target <= 1000 Follow up: What if negative numbers are allowed in the given array? How does it change the problem? What limitation we need to add to the question to allow negative numbers?
[Python 3] Faster than 96% (Super Simple!)
323
combination-sum-iv
0.521
jodoko
Medium
6,438
377
kth smallest element in a sorted matrix
class Solution: def kthSmallest(self, matrix: List[List[int]], k: int) -> int: m = len(matrix) n = len(matrix[0]) def count(m): c = 0 # count of element less than equals to 'm' i = n-1 j = 0 while i >= 0 and j < n: if matrix[i][j] > m: i -= 1 else: c += i+1 j += 1 return c low = matrix[0][0] high = matrix[n-1][n-1] while low <= high: m = (low+high)//2 cnt = count(m) if cnt < k: low = m + 1 else: cnt1 = count(m-1) if cnt1 < k: return m high = m-1 return 0
https://leetcode.com/problems/kth-smallest-element-in-a-sorted-matrix/discuss/2233868/Simple-yet-best-Interview-Code-or-Python-Code-beats-90
5
Given an n x n matrix where each of the rows and columns is sorted in ascending order, return the kth smallest element in the matrix. Note that it is the kth smallest element in the sorted order, not the kth distinct element. You must find a solution with a memory complexity better than O(n2). Example 1: Input: matrix = [[1,5,9],[10,11,13],[12,13,15]], k = 8 Output: 13 Explanation: The elements in the matrix are [1,5,9,10,11,12,13,13,15], and the 8th smallest number is 13 Example 2: Input: matrix = [[-5]], k = 1 Output: -5 Constraints: n == matrix.length == matrix[i].length 1 <= n <= 300 -109 <= matrix[i][j] <= 109 All the rows and columns of matrix are guaranteed to be sorted in non-decreasing order. 1 <= k <= n2 Follow up: Could you solve the problem with a constant memory (i.e., O(1) memory complexity)? Could you solve the problem in O(n) time complexity? The solution may be too advanced for an interview but you may find reading this paper fun.
✅ Simple yet best Interview Code | Python Code beats 90%
532
kth-smallest-element-in-a-sorted-matrix
0.616
reinkarnation
Medium
6,467
378
linked list random node
class Solution: def __init__(self, head: ListNode): """ @param head The linked list's head. Note that the head is guaranteed to be not null, so it contains at least one node. """ self.head = head # store head of linked list def getRandom(self) -> int: """ Returns a random node's value. """ cnt = 0 node = self.head while node: cnt += 1 if randint(1, cnt) == cnt: ans = node.val # reservoir sampling node = node.next return ans
https://leetcode.com/problems/linked-list-random-node/discuss/811617/Python3-reservoir-sampling
4
Given a singly linked list, return a random node's value from the linked list. Each node must have the same probability of being chosen. Implement the Solution class: Solution(ListNode head) Initializes the object with the head of the singly-linked list head. int getRandom() Chooses a node randomly from the list and returns its value. All the nodes of the list should be equally likely to be chosen. Example 1: Input ["Solution", "getRandom", "getRandom", "getRandom", "getRandom", "getRandom"] [[[1, 2, 3]], [], [], [], [], []] Output [null, 1, 3, 2, 2, 3] Explanation Solution solution = new Solution([1, 2, 3]); solution.getRandom(); // return 1 solution.getRandom(); // return 3 solution.getRandom(); // return 2 solution.getRandom(); // return 2 solution.getRandom(); // return 3 // getRandom() should return either 1, 2, or 3 randomly. Each element should have equal probability of returning. Constraints: The number of nodes in the linked list will be in the range [1, 104]. -104 <= Node.val <= 104 At most 104 calls will be made to getRandom. Follow up: What if the linked list is extremely large and its length is unknown to you? Could you solve this efficiently without using extra space?
[Python3] reservoir sampling
395
linked-list-random-node
0.596
ye15
Medium
6,513
382
ransom note
class Solution: def canConstruct(self, ransomNote, magazine): for i in set(ransomNote): if magazine.count(i) < ransomNote.count(i): return False return True
https://leetcode.com/problems/ransom-note/discuss/1346131/Easiest-python-solution-faster-than-95
35
Given two strings ransomNote and magazine, return true if ransomNote can be constructed by using the letters from magazine and false otherwise. Each letter in magazine can only be used once in ransomNote. Example 1: Input: ransomNote = "a", magazine = "b" Output: false Example 2: Input: ransomNote = "aa", magazine = "ab" Output: false Example 3: Input: ransomNote = "aa", magazine = "aab" Output: true Constraints: 1 <= ransomNote.length, magazine.length <= 105 ransomNote and magazine consist of lowercase English letters.
Easiest python solution, faster than 95%
3,500
ransom-note
0.576
mqueue
Easy
6,520
383
shuffle an array
class Solution: def __init__(self, nums: List[int]): self.arr = nums[:] # Deep Copy, Can also use Shallow Copy concept! # self.arr = nums # Shallow Copy would be something like this! def reset(self) -> List[int]: return self.arr def shuffle(self) -> List[int]: ans = self.arr[:] for i in range(len(ans)): swp_num = random.randrange(i, len(ans)) # Fisher-Yates Algorithm ans[i], ans[swp_num] = ans[swp_num], ans[i] return ans
https://leetcode.com/problems/shuffle-an-array/discuss/1673643/Python-or-Best-Optimal-Approach
6
Given an integer array nums, design an algorithm to randomly shuffle the array. All permutations of the array should be equally likely as a result of the shuffling. Implement the Solution class: Solution(int[] nums) Initializes the object with the integer array nums. int[] reset() Resets the array to its original configuration and returns it. int[] shuffle() Returns a random shuffling of the array. Example 1: Input ["Solution", "shuffle", "reset", "shuffle"] [[[1, 2, 3]], [], [], []] Output [null, [3, 1, 2], [1, 2, 3], [1, 3, 2]] Explanation Solution solution = new Solution([1, 2, 3]); solution.shuffle(); // Shuffle the array [1,2,3] and return its result. // Any permutation of [1,2,3] must be equally likely to be returned. // Example: return [3, 1, 2] solution.reset(); // Resets the array back to its original configuration [1,2,3]. Return [1, 2, 3] solution.shuffle(); // Returns the random shuffling of array [1,2,3]. Example: return [1, 3, 2] Constraints: 1 <= nums.length <= 50 -106 <= nums[i] <= 106 All the elements of nums are unique. At most 104 calls in total will be made to reset and shuffle.
{ Python } | Best Optimal Approach ✔
725
shuffle-an-array
0.577
leet_satyam
Medium
6,569
384
mini parser
class Solution: def deserialize(self, s: str) -> NestedInteger: if not s: return NestedInteger() if not s.startswith("["): return NestedInteger(int(s)) # integer ans = NestedInteger() s = s[1:-1] # strip outer "[" and "]" if s: ii = op = 0 for i in range(len(s)): if s[i] == "[": op += 1 if s[i] == "]": op -= 1 if s[i] == "," and op == 0: ans.add(self.deserialize(s[ii:i])) ii = i+1 ans.add(self.deserialize(s[ii:i+1])) return ans
https://leetcode.com/problems/mini-parser/discuss/875743/Python3-a-concise-recursive-solution
2
Given a string s represents the serialization of a nested list, implement a parser to deserialize it and return the deserialized NestedInteger. Each element is either an integer or a list whose elements may also be integers or other lists. Example 1: Input: s = "324" Output: 324 Explanation: You should return a NestedInteger object which contains a single integer 324. Example 2: Input: s = "[123,[456,[789]]]" Output: [123,[456,[789]]] Explanation: Return a NestedInteger object containing a nested list with 2 elements: 1. An integer containing value 123. 2. A nested list containing two elements: i. An integer containing value 456. ii. A nested list with one element: a. An integer containing value 789 Constraints: 1 <= s.length <= 5 * 104 s consists of digits, square brackets "[]", negative sign '-', and commas ','. s is the serialization of valid NestedInteger. All the values in the input are in the range [-106, 106].
[Python3] a concise recursive solution
178
mini-parser
0.366
ye15
Medium
6,590
385
lexicographical numbers
class Solution: def lexicalOrder(self, n: int) -> List[int]: return sorted([x for x in range(1,n+1)],key=lambda x: str(x))
https://leetcode.com/problems/lexicographical-numbers/discuss/2053392/Python-oneliner
1
Given an integer n, return all the numbers in the range [1, n] sorted in lexicographical order. You must write an algorithm that runs in O(n) time and uses O(1) extra space. Example 1: Input: n = 13 Output: [1,10,11,12,13,2,3,4,5,6,7,8,9] Example 2: Input: n = 2 Output: [1,2] Constraints: 1 <= n <= 5 * 104
Python oneliner
135
lexicographical-numbers
0.608
StikS32
Medium
6,592
386
first unique character in a string
class Solution: def firstUniqChar(self, s: str) -> int: for i in range(len(s)): if s[i] not in s[:i] and s[i] not in s[i+1:]: return i return -1
https://leetcode.com/problems/first-unique-character-in-a-string/discuss/1793386/Python-Simple-Python-Solution-With-Two-Approach
28
Given a string s, find the first non-repeating character in it and return its index. If it does not exist, return -1. Example 1: Input: s = "leetcode" Output: 0 Example 2: Input: s = "loveleetcode" Output: 2 Example 3: Input: s = "aabb" Output: -1 Constraints: 1 <= s.length <= 105 s consists of only lowercase English letters.
[ Python ] ✅✅ Simple Python Solution With Two Approach 🥳✌👍
1,600
first-unique-character-in-a-string
0.59
ASHOK_KUMAR_MEGHVANSHI
Easy
6,607
387
longest absolute file path
class Solution: def lengthLongestPath(self, s: str) -> int: paths, stack, ans = s.split('\n'), [], 0 for path in paths: p = path.split('\t') depth, name = len(p) - 1, p[-1] l = len(name) while stack and stack[-1][1] >= depth: stack.pop() if not stack: stack.append((l, depth)) else: stack.append((l+stack[-1][0], depth)) if '.' in name: ans = max(ans, stack[-1][0] + stack[-1][1]) return ans
https://leetcode.com/problems/longest-absolute-file-path/discuss/812407/Python-3-or-Stack-or-Explanation
23
Suppose we have a file system that stores both files and directories. An example of one system is represented in the following picture: Here, we have dir as the only directory in the root. dir contains two subdirectories, subdir1 and subdir2. subdir1 contains a file file1.ext and subdirectory subsubdir1. subdir2 contains a subdirectory subsubdir2, which contains a file file2.ext. In text form, it looks like this (with ⟶ representing the tab character): dir ⟶ subdir1 ⟶ ⟶ file1.ext ⟶ ⟶ subsubdir1 ⟶ subdir2 ⟶ ⟶ subsubdir2 ⟶ ⟶ ⟶ file2.ext If we were to write this representation in code, it will look like this: "dir\n\tsubdir1\n\t\tfile1.ext\n\t\tsubsubdir1\n\tsubdir2\n\t\tsubsubdir2\n\t\t\tfile2.ext". Note that the '\n' and '\t' are the new-line and tab characters. Every file and directory has a unique absolute path in the file system, which is the order of directories that must be opened to reach the file/directory itself, all concatenated by '/'s. Using the above example, the absolute path to file2.ext is "dir/subdir2/subsubdir2/file2.ext". Each directory name consists of letters, digits, and/or spaces. Each file name is of the form name.extension, where name and extension consist of letters, digits, and/or spaces. Given a string input representing the file system in the explained format, return the length of the longest absolute path to a file in the abstracted file system. If there is no file in the system, return 0. Note that the testcases are generated such that the file system is valid and no file or directory name has length 0. Example 1: Input: input = "dir\n\tsubdir1\n\tsubdir2\n\t\tfile.ext" Output: 20 Explanation: We have only one file, and the absolute path is "dir/subdir2/file.ext" of length 20. Example 2: Input: input = "dir\n\tsubdir1\n\t\tfile1.ext\n\t\tsubsubdir1\n\tsubdir2\n\t\tsubsubdir2\n\t\t\tfile2.ext" Output: 32 Explanation: We have two files: "dir/subdir1/file1.ext" of length 21 "dir/subdir2/subsubdir2/file2.ext" of length 32. We return 32 since it is the longest absolute path to a file. Example 3: Input: input = "a" Output: 0 Explanation: We do not have any files, just a single directory named "a". Constraints: 1 <= input.length <= 104 input may contain lowercase or uppercase English letters, a new line character '\n', a tab character '\t', a dot '.', a space ' ', and digits. All file and directory names have positive length.
Python 3 | Stack | Explanation
1,900
longest-absolute-file-path
0.465
idontknoooo
Medium
6,655
388
find the difference
class Solution: def findTheDifference(self, s: str, t: str) -> str: s, t = sorted(s), sorted(t) for i,j in enumerate(s): if j != t[i]: return t[i] return t[-1]
https://leetcode.com/problems/find-the-difference/discuss/379846/Three-Solutions-in-Python-3
23
You are given two strings s and t. String t is generated by random shuffling string s and then add one more letter at a random position. Return the letter that was added to t. Example 1: Input: s = "abcd", t = "abcde" Output: "e" Explanation: 'e' is the letter that was added. Example 2: Input: s = "", t = "y" Output: "y" Constraints: 0 <= s.length <= 1000 t.length == s.length + 1 s and t consist of lowercase English letters.
Three Solutions in Python 3
2,300
find-the-difference
0.603
junaidmansuri
Easy
6,673
389