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 charac...
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 ...
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): ...
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], ...
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, combinati...
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 ...
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 <= num...
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]...
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 ...
πŸ”₯ 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...
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...
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: ...
[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 squar...
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: In...
[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...
[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: ...
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 (...
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...
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: ...
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) #...
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 <= 1...
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(): n...
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 fun...
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 ...
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 i...
[ 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...
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...
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...
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 ...
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 ...
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 ...
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) ti...
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 ...
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 descen...
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 ...
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).”...
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 g...
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 ...
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. ...
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...
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...
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: ...
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...
βœ”οΈ 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 -...
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...
[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 = ...
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() ...
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...
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. Examp...
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 limi...
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 += ...
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 p...
[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 ...
βœ… 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: "...
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 Six...
[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 ...
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 pap...
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 gi...
βœ” 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 ...
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...
βœ”οΈ 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 ...
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:...
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)) ...
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. Ex...
[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...
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]...
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] Ou...
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 ...
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 cel...
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 ...
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" Ou...
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): ...
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...
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 lo...
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...
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: ...
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 = ...
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: ...
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: ["(())()","()()()...
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): # ...
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 additi...
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): ...
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...
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 grap...
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 t...
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 s...
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 ...
[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): ...
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:...
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 ...
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 t...
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 (...
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 <= 10...
[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 ra...
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: ...
βœ… 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 num...
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 ...
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. R...
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) ret...
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...
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] ...
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] ...
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: Inp...
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...
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 Expla...
[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 ...
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...
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 #...
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]...
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 ...
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 num...
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]...
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 ...
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: fligh...
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 itin...
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]) ...
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]...
[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 ...
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-clock...
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: ...
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(s...
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 ...
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 d...
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...
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 Fol...
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. Co...
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",...
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] ...
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 ...
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(f...
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...
[ 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]...
[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[...
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,...
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: ...
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 c...
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] ...
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 rec...
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 recei...
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...
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 # ...
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,...
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 -...
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(l...
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,1...
[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...
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(...
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 ...
[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 cur...
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, ...
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 waysT...
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...
[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 whil...
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: matri...
βœ… 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: """ ...
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 re...
[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 = ...
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))...
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 confi...
{ 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 ...
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 Neste...
[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 Engli...
[ 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...
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 contai...
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:...
Three Solutions in Python 3
2,300
find-the-difference
0.603
junaidmansuri
Easy
6,673
389