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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
two sum | class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
d = {}
for i, j in enumerate(nums):
r = target - j
if r in d: return [d[r], i]
d[j] = i
# An Upvote will be encouraging | https://leetcode.com/problems/two-sum/discuss/2361743/Python-Simple-Solution-oror-O(n)-Time-oror-O(n)-Space | 288 | Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
You can return the answer in any order.
Example 1:
Input: nums = [2,7,11,15], target = 9... | Python Simple Solution || O(n) Time || O(n) Space | 21,600 | two-sum | 0.491 | rajkumarerrakutti | Easy | 0 | 1 |
add two numbers | class Solution:
def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:
res = dummy = ListNode()
carry = 0
while l1 or l2:
v1, v2 = 0, 0
if l1: v1, l1 = l1.val, l1.next
if l2: v2, l2 = l2.val, l2.next
... | https://leetcode.com/problems/add-two-numbers/discuss/1835217/Python3-DUMMY-CARRY-(-**-)-Explained | 44 | You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order, and each of their nodes contains a single digit. Add the two numbers and return the sum as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
... | ✔️ [Python3] DUMMY CARRY ( •⌄• ू )✧, Explained | 7,100 | add-two-numbers | 0.398 | artod | Medium | 46 | 2 |
longest substring without repeating characters | class Solution(object):
def lengthOfLongestSubstring(self, s):
"""
:type s: str
:rtype: int abcabcbb
"""
if len(s) == 0:
return 0
seen = {}
left, right = 0, 0
longest = 1
while right < len(s):
if s[right] in seen:
... | https://leetcode.com/problems/longest-substring-without-repeating-characters/discuss/742926/Simple-Explanation-or-Concise-or-Thinking-Process-and-Example | 290 | Given a string s, find the length of the longest
substring
without repeating characters.
Example 1:
Input: s = "abcabcbb"
Output: 3
Explanation: The answer is "abc", with the length of 3.
Example 2:
Input: s = "bbbbb"
Output: 1
Explanation: The answer is "b", with the length of 1.
Example 3:
Input: s = "pwwkew"
Outpu... | Simple Explanation | Concise | Thinking Process & Example | 13,100 | longest-substring-without-repeating-characters | 0.338 | ivankatrump | Medium | 77 | 3 |
median of two sorted arrays | class Solution:
def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float:
# Get the lengths of both lists
l1,l2 = len(nums1), len(nums2)
# Determine the middle
middle = (l1 + l2) / 2
# EDGE CASE:
# If we only have 1 value (e.g. [1], []), return nums1[0] if the leng... | https://leetcode.com/problems/median-of-two-sorted-arrays/discuss/949705/Python3-two-pointer-greater9621-runtime-commented | 32 | Given two sorted arrays nums1 and nums2 of size m and n respectively, return the median of the two sorted arrays.
The overall run time complexity should be O(log (m+n)).
Example 1:
Input: nums1 = [1,3], nums2 = [2]
Output: 2.00000
Explanation: merged array = [1,2,3] and median is 2.
Example 2:
Input: nums1 = [1,2], n... | Python3 two pointer >96,21% runtime [commented] | 5,100 | median-of-two-sorted-arrays | 0.353 | tomhagen | Hard | 133 | 4 |
longest palindromic substring | class Solution:
def longestPalindrome(self, s: str) -> str:
n=len(s)
def expand_pallindrome(i,j):
while 0<=i<=j<n and s[i]==s[j]:
i-=1
j+=1
return (i+1, j)
res=(0,0)
for i in rang... | https://leetcode.com/problems/longest-palindromic-substring/discuss/2156659/Python-Easy-O(1)-Space-approach | 47 | Given a string s, return the longest
palindromic
substring
in s.
Example 1:
Input: s = "babad"
Output: "bab"
Explanation: "aba" is also a valid answer.
Example 2:
Input: s = "cbbd"
Output: "bb"
Constraints:
1 <= s.length <= 1000
s consist of only digits and English letters. | ✅ Python Easy O(1) Space approach | 6,600 | longest-palindromic-substring | 0.324 | constantine786 | Medium | 181 | 5 |
zigzag conversion | class Solution:
def convert(self, s: str, numRows: int) -> str:
if numRows == 1:
return s
row_arr = [""] * numRows
row_idx = 1
going_up = True
for ch in s:
row_arr[row_idx-1] += ch
if row_idx == numRows:
going_... | https://leetcode.com/problems/zigzag-conversion/discuss/817306/Very-simple-and-intuitive-O(n)-python-solution-with-explanation | 96 | The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility)
P A H N
A P L S I I G
Y I R
And then read line by line: "PAHNAPLSIIGYIR"
Write the code that will take a string and make this conversion ... | Very simple and intuitive O(n) python solution with explanation | 3,000 | zigzag-conversion | 0.432 | wmv3317 | Medium | 230 | 6 |
reverse integer | class Solution:
def reverse(self, x: int) -> int:
retval = int(str(abs(x))[::-1])
if(retval.bit_length()>31):
return 0
if x<0:
return -1*retval
else:
return retval | https://leetcode.com/problems/reverse-integer/discuss/1061403/Clean-pythonic-solution | 20 | Given a signed 32-bit integer x, return x with its digits reversed. If reversing x causes the value to go outside the signed 32-bit integer range [-231, 231 - 1], then return 0.
Assume the environment does not allow you to store 64-bit integers (signed or unsigned).
Example 1:
Input: x = 123
Output: 321
Example 2:
In... | Clean pythonic solution | 3,300 | reverse-integer | 0.273 | njain07 | Medium | 277 | 7 |
string to integer (atoi) | class Solution:
def myAtoi(self, s: str) -> int:
if not s:
return 0
sign = 1
integer = 0
i = 0
while i < len(s) and s[i] == ' ':
i+=1 #skipping leading white space
if i < len(s) and (s[i] == '-' or s[i] == '+'):
if s[i] == ... | https://leetcode.com/problems/string-to-integer-atoi/discuss/1510014/Python-Simple-Solution-without-Strip-beats-95 | 7 | Implement the myAtoi(string s) function, which converts a string to a 32-bit signed integer.
The algorithm for myAtoi(string s) is as follows:
Whitespace: Ignore any leading whitespace (" ").
Signedness: Determine the sign by checking if the next character is '-' or '+', assuming positivity is neither present.
Conversi... | Python Simple Solution without Strip beats 95% | 790 | string-to-integer-atoi | 0.166 | emerald19 | Medium | 331 | 8 |
palindrome number | class Solution:
def isPalindrome(self, x: int) -> bool:
if x < 0:
return False
res = 0
temp = x
while temp:
temp, n = divmod(temp, 10)
res = (res * 10) + n
return res == x | https://leetcode.com/problems/palindrome-number/discuss/2797115/Easy-Python-Solution-with-O(1)-space | 11 | Given an integer x, return true if x is a
palindrome
, and false otherwise.
Example 1:
Input: x = 121
Output: true
Explanation: 121 reads as 121 from left to right and from right to left.
Example 2:
Input: x = -121
Output: false
Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Ther... | Easy Python Solution with O(1) space | 1,900 | palindrome-number | 0.53 | tragob | Easy | 382 | 9 |
regular expression matching | class Solution:
def isMatch(self, s, p):
n = len(s)
m = len(p)
dp = [[False for _ in range (m+1)] for _ in range (n+1)]
dp[0][0] = True
for c in range(1,m+1):
if p[c-1] == '*' and c > 1:
dp[0][c] = dp[0][c-2]
for r in range(1,n+1):
for c ... | https://leetcode.com/problems/regular-expression-matching/discuss/2383634/Fastest-Solution-Explained0ms100-O(n)time-complexity-O(n)space-complexity | 10 | Given an input string s and a pattern p, implement regular expression matching with support for '.' and '*' where:
'.' Matches any single character.
'*' Matches zero or more of the preceding element.
The matching should cover the entire input string (not partial).
Example 1:
Input: s = "aa", p = "a"
Output: false
Exp... | [Fastest Solution Explained][0ms][100%] O(n)time complexity O(n)space complexity | 1,300 | regular-expression-matching | 0.282 | cucerdariancatalin | Hard | 425 | 10 |
container with most water | class Solution:
def maxArea(self, height: List[int]) -> int:
l, r, area = 0, len(height) - 1, 0
while l < r:
area = max(area, (r - l) * min(height[l], height[r]))
if height[l] < height[r]:
l += 1
else:
r -= 1
return area | https://leetcode.com/problems/container-with-most-water/discuss/1915108/Python3-GREEDY-TWO-POINTERS-~(~)-Explained | 133 | You are given an integer array height of length n. There are n vertical lines drawn such that the two endpoints of the ith line are (i, 0) and (i, height[i]).
Find two lines that together with the x-axis form a container, such that the container contains the most water.
Return the maximum amount of water a container ca... | ✔️ [Python3] GREEDY TWO POINTERS ~(˘▾˘~), Explained | 9,600 | container-with-most-water | 0.543 | artod | Medium | 446 | 11 |
integer to roman | class Solution:
def intToRoman(self, num: int) -> str:
# Creating Dictionary for Lookup
num_map = {
1: "I",
5: "V", 4: "IV",
10: "X", 9: "IX",
50: "L", 40: "XL",
100: "C", 90: "XC",
500: "D", 400: "CD",
1000... | https://leetcode.com/problems/integer-to-roman/discuss/2724200/Python's-Simple-and-Easy-to-Understand-Solution-or-99-Faster | 53 | Seven different symbols represent Roman numerals with the following values:
Symbol Value
I 1
V 5
X 10
L 50
C 100
D 500
M 1000
Roman numerals are formed by appending the conversions of decimal place values from highest to lowest. Converting a decimal place value into a Roman numeral has the following rules:
If the value... | ✔️ Python's Simple and Easy to Understand Solution | 99% Faster 🔥 | 2,600 | integer-to-roman | 0.615 | pniraj657 | Medium | 496 | 12 |
roman to integer | class Solution:
def romanToInt(self, s: str) -> int:
translations = {
"I": 1,
"V": 5,
"X": 10,
"L": 50,
"C": 100,
"D": 500,
"M": 1000
}
number = 0
s = s.replace("IV", "IIII").replace("IX", "VIIII")
... | https://leetcode.com/problems/roman-to-integer/discuss/264743/Clean-Python-beats-99.78. | 1,200 | Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M.
Symbol Value
I 1
V 5
X 10
L 50
C 100
D 500
M 1000
For example, 2 is written as II in Roman numeral, just two ones added together. 12 is written as ... | Clean Python, beats 99.78%. | 60,900 | roman-to-integer | 0.582 | hgrsd | Easy | 548 | 13 |
longest common prefix | class Solution:
def longestCommonPrefix(self, strs: List[str]) -> str:
pre = strs[0]
for i in strs:
while not i.startswith(pre):
pre = pre[:-1]
return pre | https://leetcode.com/problems/longest-common-prefix/discuss/1351149/Python-and-startswith | 72 | Write a function to find the longest common prefix string amongst an array of strings.
If there is no common prefix, return an empty string "".
Example 1:
Input: strs = ["flower","flow","flight"]
Output: "fl"
Example 2:
Input: strs = ["dog","racecar","car"]
Output: ""
Explanation: There is no common prefix among the ... | Python & startswith | 4,500 | longest-common-prefix | 0.408 | lokeshsenthilkumar | Easy | 595 | 14 |
binary tree level order traversal | class Solution:
def levelOrder(self, root: Optional[TreeNode]) -> List[List[int]]:
levels = []
def order(node, level):
if level >= len(levels):
levels.append([])
if node:
levels[level].append(node.val)
... | https://leetcode.com/problems/binary-tree-level-order-traversal/discuss/2790811/Python-solution | 0 | Given the root of a binary tree, return the level order traversal of its nodes' values. (i.e., from left to right, level by level).
Example 1:
Input: root = [3,9,20,null,null,15,7]
Output: [[3],[9,20],[15,7]]
Example 2:
Input: root = [1]
Output: [[1]]
Example 3:
Input: root = []
Output: []
Constraints:
The number o... | Python solution | 3 | binary-tree-level-order-traversal | 0.634 | maomao1010 | Medium | 613 | 102 |
binary tree zigzag level order traversal | class Solution:
def zigzagLevelOrder(self, root):
res = []
if not root: return res
zigzag = True
q = collections.deque()
q.append(root)
while q:
n = len(q)
nodesOfThisLevel = []
for i in range... | https://leetcode.com/problems/binary-tree-zigzag-level-order-traversal/discuss/2098804/Python3-Clean-Solution-using-Queue-Level-Order-Traversal | 7 | Given the root of a binary tree, return the zigzag level order traversal of its nodes' values. (i.e., from left to right, then right to left for the next level and alternate between).
Example 1:
Input: root = [3,9,20,null,null,15,7]
Output: [[3],[20,9],[15,7]]
Example 2:
Input: root = [1]
Output: [[1]]
Example 3:
Inp... | [Python3] Clean Solution using Queue Level Order Traversal | 240 | binary-tree-zigzag-level-order-traversal | 0.552 | samirpaul1 | Medium | 614 | 103 |
maximum depth of binary tree | class Solution:
def maxDepth(self, root: TreeNode) -> int:
if not root:
return 0
return max(self.maxDepth(root.left), self.maxDepth(root.right)) + 1 | https://leetcode.com/problems/maximum-depth-of-binary-tree/discuss/359949/Python-recursive-and-iterative-solution | 219 | Given the root of a binary tree, return its maximum depth.
A binary tree's maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.
Example 1:
Input: root = [3,9,20,null,null,15,7]
Output: 3
Example 2:
Input: root = [1,null,2]
Output: 2
Constraints:
The number o... | Python recursive and iterative solution | 18,300 | maximum-depth-of-binary-tree | 0.732 | amchoukir | Easy | 630 | 104 |
construct binary tree from preorder and inorder traversal | class Solution:
def buildTree(self, preorder: List[int], inorder: List[int]) -> TreeNode:
loc = {x : i for i, x in enumerate(inorder)}
root = None
stack = []
for x in preorder:
if not root: root = node = TreeNode(x)
elif loc[x] < loc[node.val]:
... | https://leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/discuss/689647/Python3-stack-O(N) | 7 | Given two integer arrays preorder and inorder where preorder is the preorder traversal of a binary tree and inorder is the inorder traversal of the same tree, construct and return the binary tree.
Example 1:
Input: preorder = [3,9,20,15,7], inorder = [9,3,15,20,7]
Output: [3,9,20,null,null,15,7]
Example 2:
Input: pre... | [Python3] stack O(N) | 371 | construct-binary-tree-from-preorder-and-inorder-traversal | 0.609 | ye15 | Medium | 671 | 105 |
construct binary tree from inorder and postorder traversal | class Solution:
def buildTree(self, inorder, postorder):
inorderIndexDict = {ch : i for i, ch in enumerate(inorder)}
self.rootIndex = len(postorder) - 1
def solve(l, r):
if l > r: return None
root = TreeNode(postorder[self.rootIndex])
... | https://leetcode.com/problems/construct-binary-tree-from-inorder-and-postorder-traversal/discuss/2098606/Python3-O(n)-Time-O(1)-Space-Solution-faster-than-95 | 3 | Given two integer arrays inorder and postorder where inorder is the inorder traversal of a binary tree and postorder is the postorder traversal of the same tree, construct and return the binary tree.
Example 1:
Input: inorder = [9,3,15,20,7], postorder = [9,15,7,20,3]
Output: [3,9,20,null,null,15,7]
Example 2:
Input:... | [Python3] O(n) Time, O(1) Space Solution faster than 95% | 159 | construct-binary-tree-from-inorder-and-postorder-traversal | 0.575 | samirpaul1 | Medium | 707 | 106 |
binary tree level order traversal ii | class Solution:
def helper(self, result, depth, node):
if not node:
return
if len(result) < depth:
result.append([])
result[depth-1].append(node.val)
self.helper(result, depth+1, node.left)
self.helper(result, depth+1, node.right)... | https://leetcode.com/problems/binary-tree-level-order-traversal-ii/discuss/359962/Python-recursive-and-iterative | 4 | Given the root of a binary tree, return the bottom-up level order traversal of its nodes' values. (i.e., from left to right, level by level from leaf to root).
Example 1:
Input: root = [3,9,20,null,null,15,7]
Output: [[15,7],[9,20],[3]]
Example 2:
Input: root = [1]
Output: [[1]]
Example 3:
Input: root = []
Output: []... | Python recursive and iterative | 519 | binary-tree-level-order-traversal-ii | 0.604 | amchoukir | Medium | 717 | 107 |
convert sorted array to binary search tree | class Solution(object):
def sortedArrayToBST(self, nums):
# Base condition...
if len(nums) == 0:
return None
# set the middle node...
mid = len(nums)//2
# Initialise root node with value same as nums[mid]
root = TreeNode(nums[mid])
# Assign left su... | https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree/discuss/2428167/Easy-oror-0-ms-oror-100-oror-Fully-Explained-oror-(Java-C%2B%2B-Python-JS-C-Python3) | 19 | Given an integer array nums where the elements are sorted in ascending order, convert it to a
height-balanced
binary search tree.
Example 1:
Input: nums = [-10,-3,0,5,9]
Output: [0,-3,9,-10,null,5]
Explanation: [0,-10,5,null,-3,null,9] is also accepted:
Example 2:
Input: nums = [1,3]
Output: [3,1]
Explanation: [1,nul... | Easy || 0 ms || 100% || Fully Explained || (Java, C++, Python, JS, C, Python3) | 900 | convert-sorted-array-to-binary-search-tree | 0.692 | PratikSen07 | Easy | 735 | 108 |
convert sorted list to binary search tree | class Solution:
l = 'left'
r = 'right'
def sortedListToBST(self, head: Optional[ListNode]) -> Optional[TreeNode]:
if not head: return None
nums = []
while head:
nums.append(head.val)
head = head.next
mid = len(nums) // 2
... | https://leetcode.com/problems/convert-sorted-list-to-binary-search-tree/discuss/2767308/Python-beats-86-(recursive-solution) | 2 | Given the head of a singly linked list where elements are sorted in ascending order, convert it to a
height-balanced
binary search tree.
Example 1:
Input: head = [-10,-3,0,5,9]
Output: [0,-3,9,-10,null,5]
Explanation: One possible answer is [0,-3,9,-10,null,5], which represents the shown height balanced BST.
Example ... | Python beats 86% (recursive solution) | 150 | convert-sorted-list-to-binary-search-tree | 0.574 | farruhzokirov00 | Medium | 759 | 109 |
balanced binary tree | class Solution(object):
def isBalanced(self, root):
return (self.Height(root) >= 0)
def Height(self, root):
if root is None: return 0
leftheight, rightheight = self.Height(root.left), self.Height(root.right)
if leftheight < 0 or rightheight < 0 or abs(leftheight - rightheight) >... | https://leetcode.com/problems/balanced-binary-tree/discuss/2428871/Very-Easy-oror-100-oror-Fully-Explained-(C%2B%2B-Java-Python-JavaScript-Python3) | 83 | Given a binary tree, determine if it is
height-balanced
.
Example 1:
Input: root = [3,9,20,null,null,15,7]
Output: true
Example 2:
Input: root = [1,2,2,3,3,null,null,4,4]
Output: false
Example 3:
Input: root = []
Output: true
Constraints:
The number of nodes in the tree is in the range [0, 5000].
-104 <= Node.val <... | Very Easy || 100% || Fully Explained (C++, Java, Python, JavaScript, Python3) | 6,700 | balanced-binary-tree | 0.483 | PratikSen07 | Easy | 780 | 110 |
minimum depth of binary tree | class Solution(object):
def minDepth(self, root):
# Base case...
# If the subtree is empty i.e. root is NULL, return depth as 0...
if root is None: return 0
# Initialize the depth of two subtrees...
leftDepth = self.minDepth(root.left)
rightDepth = self.minDepth(root... | https://leetcode.com/problems/minimum-depth-of-binary-tree/discuss/2429057/Very-Easy-oror-100-oror-Fully-Explained-(C%2B%2B-Java-Python-JS-C-Python3) | 32 | Given a binary tree, find its minimum depth.
The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.
Note: A leaf is a node with no children.
Example 1:
Input: root = [3,9,20,null,null,15,7]
Output: 2
Example 2:
Input: root = [2,null,3,null,4,null,5,null,6]
O... | Very Easy || 100% || Fully Explained (C++, Java, Python, JS, C, Python3) | 2,200 | minimum-depth-of-binary-tree | 0.437 | PratikSen07 | Easy | 804 | 111 |
path sum | class Solution:
"""
Time: O(n)
Memory: O(n)
"""
def hasPathSum(self, root: Optional[TreeNode], target: int) -> bool:
if root is None:
return False
if root.left is None and root.right is None:
return target == root.val
return self.hasPathSum( root.le... | https://leetcode.com/problems/path-sum/discuss/2658792/Python-Elegant-and-Short-or-DFS | 10 | Given the root of a binary tree and an integer targetSum, return true if the tree has a root-to-leaf path such that adding up all the values along the path equals targetSum.
A leaf is a node with no children.
Example 1:
Input: root = [5,4,8,11,null,13,4,7,2,null,null,null,1], targetSum = 22
Output: true
Explanation: ... | Python Elegant & Short | DFS | 422 | path-sum | 0.477 | Kyrylo-Ktl | Easy | 837 | 112 |
path sum ii | class Solution:
def pathSum(self, R: TreeNode, S: int) -> List[List[int]]:
A, P = [], []
def dfs(N):
if N == None: return
P.append(N.val)
if (N.left,N.right) == (None,None) and sum(P) == S: A.append(list(P))
else: dfs(N.left), dfs(N.right)
... | https://leetcode.com/problems/path-sum-ii/discuss/484120/Python-3-(beats-~100)-(nine-lines)-(DFS) | 9 | Given the root of a binary tree and an integer targetSum, return all root-to-leaf paths where the sum of the node values in the path equals targetSum. Each path should be returned as a list of the node values, not node references.
A root-to-leaf path is a path starting from the root and ending at any leaf node. A leaf ... | Python 3 (beats ~100%) (nine lines) (DFS) | 2,200 | path-sum-ii | 0.567 | junaidmansuri | Medium | 871 | 113 |
flatten binary tree to linked list | class Solution:
def __init__(self):
self.prev = None
def flatten(self, root: Optional[TreeNode]) -> None:
if not root: return
self.flatten(root.right)
self.flatten(root.left)
root.right = self.prev
root.left = None
self.prev = root | https://leetcode.com/problems/flatten-binary-tree-to-linked-list/discuss/2340445/Python-or-intuitive-explained-or-O(1)-space-ignoring-recursion-stack-or-O(n)-time | 7 | Given the root of a binary tree, flatten the tree into a "linked list":
The "linked list" should use the same TreeNode class where the right child pointer points to the next node in the list and the left child pointer is always null.
The "linked list" should be in the same order as a pre-order traversal of the binary t... | Python | intuitive, explained | O(1) space ignoring recursion stack | O(n) time | 223 | flatten-binary-tree-to-linked-list | 0.612 | mync | Medium | 899 | 114 |
distinct subsequences | class Solution:
def numDistinct(self, s: str, t: str) -> int:
m = len(s)
n = len(t)
dp = [[0] * (n+1) for _ in range(m+1)]
for i in range(m+1):
dp[i][0] = 1
"""redundant, as we have initialised dp table with full of zeros"""
# for i in ra... | https://leetcode.com/problems/distinct-subsequences/discuss/1472969/Python-Bottom-up-DP-Explained | 6 | Given two strings s and t, return the number of distinct subsequences of s which equals t.
The test cases are generated so that the answer fits on a 32-bit signed integer.
Example 1:
Input: s = "rabbbit", t = "rabbit"
Output: 3
Explanation:
As shown below, there are 3 ways you can generate "rabbit" from s.
rabbbit
ra... | Python - Bottom up DP - Explained | 475 | distinct-subsequences | 0.439 | ajith6198 | Hard | 924 | 115 |
populating next right pointers in each node | class Solution:
def connect(self, root: 'Node') -> 'Node':
# edge case check
if not root:
return None
# initialize the queue with root node (for level order traversal)
queue = collections.deque([root])
# start the traversal
while queue:
... | https://leetcode.com/problems/populating-next-right-pointers-in-each-node/discuss/719347/Python-Solution-O(1)-and-O(n)-memory. | 10 | You are given a perfect binary tree where all leaves are on the same level, and every parent has two children. The binary tree has the following definition:
struct Node {
int val;
Node *left;
Node *right;
Node *next;
}
Populate each next pointer to point to its next right node. If there is no next right node, t... | Python Solution O(1) and O(n) memory. | 534 | populating-next-right-pointers-in-each-node | 0.596 | darshan_22 | Medium | 956 | 116 |
populating next right pointers in each node ii | class Solution:
def connect(self, root: 'Node') -> 'Node':
if not root:
return None
q = deque()
q.append(root)
dummy=Node(-999) # to initialize with a not null prev
while q:
length=len(q) # find level length
prev=dummy
... | https://leetcode.com/problems/populating-next-right-pointers-in-each-node-ii/discuss/2033286/Python-Easy%3A-BFS-and-O(1)-Space-with-Explanation | 39 | Given a binary tree
struct Node {
int val;
Node *left;
Node *right;
Node *next;
}
Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to NULL.
Initially, all next pointers are set to NULL.
Example 1:
Input: root = [1,2,3,4,5,null,7]
Output... | Python Easy: BFS and O(1) Space with Explanation | 3,000 | populating-next-right-pointers-in-each-node-ii | 0.498 | constantine786 | Medium | 996 | 117 |
pascals triangle | class Solution:
def generate(self, numRows: int) -> List[List[int]]:
l=[0]*numRows
for i in range(numRows):
l[i]=[0]*(i+1)
l[i][0]=1
l[i][i]=1
for j in range(1,i):
l[i][j]=l[i-1][j-1]+l[i-1][j]
return l | https://leetcode.com/problems/pascals-triangle/discuss/1490520/Python3-easy-code-faster-than-96.67 | 44 | Given an integer numRows, return the first numRows of Pascal's triangle.
In Pascal's triangle, each number is the sum of the two numbers directly above it as shown:
Example 1:
Input: numRows = 5
Output: [[1],[1,1],[1,2,1],[1,3,3,1],[1,4,6,4,1]]
Example 2:
Input: numRows = 1
Output: [[1]]
Constraints:
1 <= numRows <... | Python3 easy code- faster than 96.67% | 3,600 | pascals-triangle | 0.694 | Rosh_65 | Easy | 1,033 | 118 |
pascals triangle ii | class Solution:
def getRow(self, rowIndex: int) -> List[int]:
if rowIndex == 0:
# Base case
return [1]
elif rowIndex == 1:
# Base case
return [1, 1]
else:
# General case:
last_row = self.getRow... | https://leetcode.com/problems/pascals-triangle-ii/discuss/467945/Pythonic-O(-k-)-space-sol.-based-on-math-formula-90%2B | 15 | Given an integer rowIndex, return the rowIndexth (0-indexed) row of the Pascal's triangle.
In Pascal's triangle, each number is the sum of the two numbers directly above it as shown:
Example 1:
Input: rowIndex = 3
Output: [1,3,3,1]
Example 2:
Input: rowIndex = 0
Output: [1]
Example 3:
Input: rowIndex = 1
Output: [1,1... | Pythonic O( k ) space sol. based on math formula, 90%+ | 1,800 | pascals-triangle-ii | 0.598 | brianchiang_tw | Easy | 1,084 | 119 |
triangle | class Solution:
def minimumTotal(self, triangle: List[List[int]]) -> int:
for i in range(1, len(triangle)): # for each row in triangle (skipping the first),
for j in range(i+1): # loop through each element in the row
triangle[i][j] += min(triangle[i-1][j-(j==i)], # mi... | https://leetcode.com/problems/triangle/discuss/2144882/Python-In-place-DP-with-Explanation | 18 | Given a triangle array, return the minimum path sum from top to bottom.
For each step, you may move to an adjacent number of the row below. More formally, if you are on index i on the current row, you may move to either index i or index i + 1 on the next row.
Example 1:
Input: triangle = [[2],[3,4],[6,5,7],[4,1,8,3]]... | [Python] In-place DP with Explanation | 1,400 | triangle | 0.54 | zayne-siew | Medium | 1,132 | 120 |
best time to buy and sell stock | class Solution(object):
def maxProfit(self, prices):
n = len(prices)
dp = [0]*n # initializing the dp table
dp[0] = [prices[0],0] # filling the the first dp table --> low_price = prices[0] max_profit=0
min_price = max_profit = 0
# Note that ---> indixing the dp table --> dp[i... | https://leetcode.com/problems/best-time-to-buy-and-sell-stock/discuss/1545423/Python-easy-to-understand-solution-with-explanation-%3A-Tracking-and-Dynamic-programming | 58 | You are given an array prices where prices[i] is the price of a given stock on the ith day.
You want to maximize your profit by choosing a single day to buy one stock and choosing a different day in the future to sell that stock.
Return the maximum profit you can achieve from this transaction. If you cannot achieve any... | Python easy to understand solution with explanation : Tracking and Dynamic programming | 3,200 | best-time-to-buy-and-sell-stock | 0.544 | Abeni | Easy | 1,190 | 121 |
best time to buy and sell stock ii | class Solution:
def maxProfit(self, prices: List[int]) -> int:
@cache
def trade(day_d):
if day_d == 0:
# Hold on day_#0 = buy stock at the price of day_#0
# Not-hold on day_#0 = doing nothing on day_#0
... | https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/discuss/2040292/O(n)timeBEATS-99.97-MEMORYSPEED-0ms-MAY-2022 | 12 | You are given an integer array prices where prices[i] is the price of a given stock on the ith day.
On each day, you may decide to buy and/or sell the stock. You can only hold at most one share of the stock at any time. However, you can buy it then immediately sell it on the same day.
Find and return the maximum profit... | O(n)time/BEATS 99.97% MEMORY/SPEED 0ms MAY 2022 | 605 | best-time-to-buy-and-sell-stock-ii | 0.634 | cucerdariancatalin | Medium | 1,247 | 122 |
best time to buy and sell stock iii | class Solution:
def maxProfit(self, prices: List[int]) -> int:
buy, sell = [inf]*2, [0]*2
for x in prices:
for i in range(2):
if i: buy[i] = min(buy[i], x - sell[i-1])
else: buy[i] = min(buy[i], x)
sell[i] = max(sell[i], x - buy[i])
... | https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iii/discuss/2040316/O(n)timeBEATS-99.97-MEMORYSPEED-0ms-MAY-2022 | 16 | 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 at most two transactions.
Note: You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again).
Example 1:
Input: price... | O(n)time/BEATS 99.97% MEMORY/SPEED 0ms MAY 2022 | 821 | best-time-to-buy-and-sell-stock-iii | 0.449 | cucerdariancatalin | Hard | 1,306 | 123 |
binary tree maximum path sum | class Solution:
def __init__(self):
self.maxSum = float('-inf')
def maxPathSum(self, root: TreeNode) -> int:
def traverse(root):
if root:
left = traverse(root.left)
right = traverse(root.right)
self.maxSum = max(self.maxSum,root.val, ro... | https://leetcode.com/problems/binary-tree-maximum-path-sum/discuss/2040330/O(n)timeBEATS-99.97-MEMORYSPEED-0ms-MAY-2022 | 17 | A path in a binary tree is a sequence of nodes where each pair of adjacent nodes in the sequence has an edge connecting them. A node can only appear in the sequence at most once. Note that the path does not need to pass through the root.
The path sum of a path is the sum of the node's values in the path.
Given the root... | O(n)time/BEATS 99.97% MEMORY/SPEED 0ms MAY 2022 | 1,100 | binary-tree-maximum-path-sum | 0.385 | cucerdariancatalin | Hard | 1,335 | 124 |
valid palindrome | class Solution:
def isPalindrome(self, s: str) -> bool:
s = [i for i in s.lower() if i.isalnum()]
return s == s[::-1] | https://leetcode.com/problems/valid-palindrome/discuss/350929/Solution-in-Python-3-(beats-~100)-(two-lines)-(-O(1)-solution-as-well-) | 50 | A phrase is a palindrome if, after converting all uppercase letters into lowercase letters and removing all non-alphanumeric characters, it reads the same forward and backward. Alphanumeric characters include letters and numbers.
Given a string s, return true if it is a palindrome, or false otherwise.
Example 1:
Inpu... | Solution in Python 3 (beats ~100%) (two lines) ( O(1) solution as well ) | 8,600 | valid-palindrome | 0.437 | junaidmansuri | Easy | 1,367 | 125 |
word ladder ii | class Solution:
def findLadders(self, beginWord: str, endWord: str, wordList: List[str]) -> List[List[str]]:
d = defaultdict(list)
for word in wordList:
for i in range(len(word)):
d[word[:i]+"*"+word[i+1:]].append(word)
if endWord not in wordList:
return []
visited1 = defaultdict(list)
q... | https://leetcode.com/problems/word-ladder-ii/discuss/2422401/46ms-Python-97-Faster-Working-Multiple-solutions-95-memory-efficient-solution | 35 | A transformation sequence from word beginWord to word endWord using a dictionary wordList is a sequence of words beginWord -> s1 -> s2 -> ... -> sk such that:
Every adjacent pair of words differs by a single letter.
Every si for 1 <= i <= k is in wordList. Note that beginWord does not need to be in wordList.
sk == endW... | 46ms Python 97 Faster Working Multiple solutions 95% memory efficient solution | 2,800 | word-ladder-ii | 0.276 | anuvabtest | Hard | 1,418 | 126 |
word ladder | class Solution(object):
def ladderLength(self, beginWord, endWord, wordList):
graph = defaultdict(list)
for word in wordList:
for index in range(len(beginWord)):
graph[word[:index] + "_" + word[index+1:]].append(word)
queue = deque()
queue.append((beginW... | https://leetcode.com/problems/word-ladder/discuss/1332551/Elegant-Python-Iterative-BFS | 4 | A transformation sequence from word beginWord to word endWord using a dictionary wordList is a sequence of words beginWord -> s1 -> s2 -> ... -> sk such that:
Every adjacent pair of words differs by a single letter.
Every si for 1 <= i <= k is in wordList. Note that beginWord does not need to be in wordList.
sk == endW... | Elegant Python Iterative BFS | 366 | word-ladder | 0.368 | soma28 | Hard | 1,434 | 127 |
longest consecutive sequence | class Node:
def __init__(self, val):
self.val = val
self.parent = self
self.size = 1
class UnionFind:
def find(self, node):
if node.parent != node:
node.parent = self.find(node.parent)
return node.parent
def union(self, node1, node2):
... | https://leetcode.com/problems/longest-consecutive-sequence/discuss/1109808/Python-Clean-Union-Find-with-explanation | 21 | Given an unsorted array of integers nums, return the length of the longest consecutive elements sequence.
You must write an algorithm that runs in O(n) time.
Example 1:
Input: nums = [100,4,200,1,3,2]
Output: 4
Explanation: The longest consecutive elements sequence is [1, 2, 3, 4]. Therefore its length is 4.
Example ... | [Python] Clean Union Find with explanation | 1,800 | longest-consecutive-sequence | 0.489 | l3arner | Medium | 1,459 | 128 |
sum root to leaf numbers | class Solution:
def sumNumbers(self, root: Optional[TreeNode]) -> int:
def helper(node, num):
if node is None:
return 0
num = num * 10 + node.val
if node.left is None and node.right is None:
return num
return helper(node.left, n... | https://leetcode.com/problems/sum-root-to-leaf-numbers/discuss/1557540/Python-99-speed-99-memory | 4 | You are given the root of a binary tree containing digits from 0 to 9 only.
Each root-to-leaf path in the tree represents a number.
For example, the root-to-leaf path 1 -> 2 -> 3 represents the number 123.
Return the total sum of all root-to-leaf numbers. Test cases are generated so that the answer will fit in a 32-bit... | Python 99% speed, 99% memory | 391 | sum-root-to-leaf-numbers | 0.588 | dereky4 | Medium | 1,509 | 129 |
surrounded regions | class Solution:
def dfs(self,board,i,j):
if i<0 or j<0 or i>=len(board) or j>=len(board[0]) or board[i][j]!='O':
return
board[i][j]='$' # converting to a dollar sign
self.dfs(board,i+1,j)
self.dfs(board,i-1,j)
self.dfs(board,i,j+1... | https://leetcode.com/problems/surrounded-regions/discuss/558746/Python-DFS-Easy-solution-with-comments | 12 | Given an m x n matrix board containing 'X' and 'O', capture all regions that are 4-directionally surrounded by 'X'.
A region is captured by flipping all 'O's into 'X's in that surrounded region.
Example 1:
Input: board = [["X","X","X","X"],["X","O","O","X"],["X","X","O","X"],["X","O","X","X"]]
Output: [["X","X","X","... | Python DFS Easy solution with comments | 440 | surrounded-regions | 0.361 | JoyRafatAshraf | Medium | 1,541 | 130 |
palindrome partitioning | class Solution(object):
@cache # the memory trick can save some time
def partition(self, s):
if not s: return [[]]
ans = []
for i in range(1, len(s) + 1):
if s[:i] == s[:i][::-1]: # prefix is a palindrome
for suf in self.partition(s[i:]): # process suffix r... | https://leetcode.com/problems/palindrome-partitioning/discuss/1667786/Python-Simple-Recursion-oror-Detailed-Explanation-oror-Easy-to-Understand | 209 | Given a string s, partition s such that every
substring
of the partition is a
palindrome
. Return all possible palindrome partitioning of s.
Example 1:
Input: s = "aab"
Output: [["a","a","b"],["aa","b"]]
Example 2:
Input: s = "a"
Output: [["a"]]
Constraints:
1 <= s.length <= 16
s contains only lowercase English let... | ✅ [Python] Simple Recursion || Detailed Explanation || Easy to Understand | 9,200 | palindrome-partitioning | 0.626 | linfq | Medium | 1,593 | 131 |
palindrome partitioning ii | class Solution:
def minCut(self, s: str) -> int:
#pre-processing
palin = dict()
for k in range(len(s)):
for i, j in (k, k), (k, k+1):
while 0 <= i and j < len(s) and s[i] == s[j]:
palin.setdefault(i, []).append(j)
i, j = i-... | https://leetcode.com/problems/palindrome-partitioning-ii/discuss/713271/Python3-dp-(top-down-and-bottom-up) | 2 | Given a string s, partition s such that every
substring
of the partition is a
palindrome
.
Return the minimum cuts needed for a palindrome partitioning of s.
Example 1:
Input: s = "aab"
Output: 1
Explanation: The palindrome partitioning ["aa","b"] could be produced using 1 cut.
Example 2:
Input: s = "a"
Output: 0
Exa... | [Python3] dp (top-down & bottom-up) | 131 | palindrome-partitioning-ii | 0.337 | ye15 | Hard | 1,633 | 132 |
clone graph | class Solution:
def cloneGraph(self, node: 'Node') -> 'Node':
if not node: return node
q, clones = deque([node]), {node.val: Node(node.val, [])}
while q:
cur = q.popleft()
cur_clone = clones[cur.val]
for ngbr in cur.neighbors:
... | https://leetcode.com/problems/clone-graph/discuss/1792858/Python3-ITERATIVE-BFS-(beats-98)-'less()greater''-Explained | 181 | Given a reference of a node in a connected undirected graph.
Return a deep copy (clone) of the graph.
Each node in the graph contains a value (int) and a list (List[Node]) of its neighbors.
class Node {
public int val;
public List<Node> neighbors;
}
Test case format:
For simplicity, each node's value is the s... | ✔️ [Python3] ITERATIVE BFS (beats 98%) ,、’`<(❛ヮ❛✿)>,、’`’`,、, Explained | 15,100 | clone-graph | 0.509 | artod | Medium | 1,641 | 133 |
gas station | class Solution:
def canCompleteCircuit(self, gas: List[int], cost: List[int]) -> int:
# base case
if sum(gas) - sum(cost) < 0:
return -1
gas_tank = 0 # gas available in car till now
start_index = 0 # Consider first gas station as starting point
for i in range(len(gas)):
gas_tank += gas[i] - cos... | https://leetcode.com/problems/gas-station/discuss/1276287/Simple-one-pass-python-solution | 9 | There are n gas stations along a circular route, where the amount of gas at the ith station is gas[i].
You have a car with an unlimited gas tank and it costs cost[i] of gas to travel from the ith station to its next (i + 1)th station. You begin the journey with an empty tank at one of the gas stations.
Given two intege... | Simple one pass python solution | 796 | gas-station | 0.451 | nandanabhishek | Medium | 1,676 | 134 |
candy | class Solution:
def candy(self, ratings: List[int]) -> int:
n=len(ratings)
temp = [1]*n
for i in range(1,n):
if(ratings[i]>ratings[i-1]):
temp[i]=temp[i-1]+1
if(n>1):
if(ratings[0]>ratings[1]):
temp[0]=2
... | https://leetcode.com/problems/candy/discuss/2234828/Python-oror-Two-pass-oror-explanation-oror-intuition-oror-greedy | 11 | There are n children standing in a line. Each child is assigned a rating value given in the integer array ratings.
You are giving candies to these children subjected to the following requirements:
Each child must have at least one candy.
Children with a higher rating get more candies than their neighbors.
Return the mi... | Python || Two pass || explanation || intuition || greedy | 1,200 | candy | 0.408 | palashbajpai214 | Hard | 1,707 | 135 |
single number | class Solution(object):
def singleNumber(self, nums):
# Initialize the unique number...
uniqNum = 0;
# TRaverse all elements through the loop...
for idx in nums:
# Concept of XOR...
uniqNum ^= idx;
return uniqNum; # Return the unique number... | https://leetcode.com/problems/single-number/discuss/2438883/Very-Easy-oror-0-ms-oror100oror-Fully-Explained-(Java-C%2B%2B-Python-JS-C-Python3) | 24 | Given a non-empty array of integers nums, every element appears twice except for one. Find that single one.
You must implement a solution with a linear runtime complexity and use only constant extra space.
Example 1:
Input: nums = [2,2,1]
Output: 1
Example 2:
Input: nums = [4,1,2,1,2]
Output: 4
Example 3:
Input: nums... | Very Easy || 0 ms ||100%|| Fully Explained (Java, C++, Python, JS, C, Python3) | 2,100 | single-number | 0.701 | PratikSen07 | Easy | 1,747 | 136 |
single number ii | class Solution(object):
def singleNumber(self, nums):
a, b = 0, 0
for x in nums:
a, b = (~x&a&~b)|(x&~a&b), ~a&(x^b)
return b | https://leetcode.com/problems/single-number-ii/discuss/1110333/3-python-solutions-with-different-approaches | 9 | Given an integer array nums where every element appears three times except for one, which appears exactly once. Find the single element and return it.
You must implement a solution with a linear runtime complexity and use only constant extra space.
Example 1:
Input: nums = [2,2,3,2]
Output: 3
Example 2:
Input: nums =... | 3 python solutions with different approaches | 796 | single-number-ii | 0.579 | mritunjoyhalder79 | Medium | 1,796 | 137 |
copy list with random pointer | class Solution:
def copyRandomList(self, head: 'Optional[Node]') -> 'Optional[Node]':
hm, zero = dict(), Node(0)
cur, copy = head, zero
while cur:
copy.next = Node(cur.val)
hm[cur] = copy.next
cur, copy = cur.next, copy.next
c... | https://leetcode.com/problems/copy-list-with-random-pointer/discuss/1841010/Python3-JUST-TWO-STEPS-()-Explained | 43 | A linked list of length n is given such that each node contains an additional random pointer, which could point to any node in the list, or null.
Construct a deep copy of the list. The deep copy should consist of exactly n brand new nodes, where each new node has its value set to the value of its corresponding original... | ✔️ [Python3] JUST TWO STEPS ヾ(´▽`;)ゝ, Explained | 1,700 | copy-list-with-random-pointer | 0.506 | artod | Medium | 1,827 | 138 |
word break | class Solution:
def wordBreak(self, s, wordDict):
dp = [False]*(len(s)+1)
dp[0] = True
for i in range(1, len(s)+1):
for j in range(i):
if dp[j] and s[j:i] in wordDict:
dp[i] = True
break
return dp[-1] | https://leetcode.com/problems/word-break/discuss/748479/Python3-Solution-with-a-Detailed-Explanation-Word-Break | 51 | Given a string s and a dictionary of strings wordDict, return true if s can be segmented into a space-separated sequence of one or more dictionary words.
Note that the same word in the dictionary may be reused multiple times in the segmentation.
Example 1:
Input: s = "leetcode", wordDict = ["leet","code"]
Output: tru... | Python3 Solution with a Detailed Explanation - Word Break | 4,600 | word-break | 0.455 | peyman_np | Medium | 1,863 | 139 |
word break ii | class Solution(object):
def wordBreak(self, s, wordDict):
"""
:type s: str
:type wordDict: List[str]
:rtype: List[str]
"""
def wordsEndingIn(i):
if i == len(s):
return [""]
ans = []
for j in range(i+1, len(s)+1):
... | https://leetcode.com/problems/word-break-ii/discuss/744674/Diagrammatic-Python-Intuitive-Solution-with-Example | 10 | Given a string s and a dictionary of strings wordDict, add spaces in s to construct a sentence where each word is a valid dictionary word. Return all such possible sentences in any order.
Note that the same word in the dictionary may be reused multiple times in the segmentation.
Example 1:
Input: s = "catsanddog", wo... | Diagrammatic Python Intuitive Solution with Example | 526 | word-break-ii | 0.446 | ivankatrump | Hard | 1,916 | 140 |
linked list cycle | class Solution(object):
def hasCycle(self, head):
"""
:type head: ListNode
:rtype: bool
"""
if head is None or head.next is None return False
slow_ref = head
fast_ref = head
while fast_ref and fast_ref.next:
slow_ref = slow_ref.next
f... | https://leetcode.com/problems/linked-list-cycle/discuss/1047819/Easy-in-Pythonor-O(1)-or-Beats-91 | 13 | Given head, the head of a linked list, determine if the linked list has a cycle in it.
There is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the next pointer. Internally, pos is used to denote the index of the node that tail's next pointer is connected t... | Easy in Python| O(1) | Beats 91% | 948 | linked-list-cycle | 0.47 | vsahoo | Easy | 1,966 | 141 |
linked list cycle ii | class Solution:
def detectCycle(self, head: Optional[ListNode]) -> Optional[ListNode]:
fast, slow = head, head
while(fast and fast.next):
fast = fast.next.next
slow = slow.next
if(fast == slow):
slow = head
while(slow is not fast):
... | https://leetcode.com/problems/linked-list-cycle-ii/discuss/2184711/O(1)-Space-Python-solution-with-clear-explanation-faster-than-90-solutions | 30 | Given the head of a linked list, return the node where the cycle begins. If there is no cycle, return null.
There is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the next pointer. Internally, pos is used to denote the index of the node that tail's next p... | O(1) Space Python solution with clear explanation faster than 90% solutions | 844 | linked-list-cycle-ii | 0.465 | saiamrit | Medium | 2,010 | 142 |
reorder list | class Solution:
def reorderList(self, head: Optional[ListNode]) -> None:
if not head.next or not head.next.next:
return
# search for the middle
slow, fast = head, head
while fast.next and fast.next.next:
slow = slow.next
fast = fast.next.n... | https://leetcode.com/problems/reorder-list/discuss/1640529/Python3-ONE-PASS-L(o)-Explained | 5 | You are given the head of a singly linked-list. The list can be represented as:
L0 → L1 → … → Ln - 1 → Ln
Reorder the list to be on the following form:
L0 → Ln → L1 → Ln - 1 → L2 → Ln - 2 → …
You may not modify the values in the list's nodes. Only nodes themselves may be changed.
Example 1:
Input: head = [1,2,3,4]
Ou... | ✔️ [Python3] ONE PASS, L(・o・)」, Explained | 482 | reorder-list | 0.513 | artod | Medium | 2,043 | 143 |
binary tree preorder traversal | class Solution:
def preorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
ans = []
stack = [root]
while stack:
temp = stack.pop()
if temp:
ans.append(temp.val)
stack.append(temp.right) #as we are using st... | https://leetcode.com/problems/binary-tree-preorder-traversal/discuss/1403244/3-Simple-Python-solutions | 14 | Given the root of a binary tree, return the preorder traversal of its nodes' values.
Example 1:
Input: root = [1,null,2,3]
Output: [1,2,3]
Example 2:
Input: root = []
Output: []
Example 3:
Input: root = [1]
Output: [1]
Constraints:
The number of nodes in the tree is in the range [0, 100].
-100 <= Node.val <= 100
... | 3 Simple Python solutions | 1,100 | binary-tree-preorder-traversal | 0.648 | shraddhapp | Easy | 2,070 | 144 |
binary tree postorder traversal | class Solution(object):
def postorderTraversal(self, root):
# Base case...
if not root: return []
# Create an array list to store the solution result...
sol = []
# Create an empty stack and push the root node...
bag = [root]
# Loop till stack is empty...
... | https://leetcode.com/problems/binary-tree-postorder-traversal/discuss/2443702/Easy-oror-Recursive-and-Iterative-oror-100-oror-Explained-(Java-C%2B%2B-Python-Python3) | 16 | Given the root of a binary tree, return the postorder traversal of its nodes' values.
Example 1:
Input: root = [1,null,2,3]
Output: [3,2,1]
Example 2:
Input: root = []
Output: []
Example 3:
Input: root = [1]
Output: [1]
Constraints:
The number of the nodes in the tree is in the range [0, 100].
-100 <= Node.val <= 1... | Easy || Recursive & Iterative || 100% || Explained (Java, C++, Python, Python3) | 1,100 | binary-tree-postorder-traversal | 0.668 | PratikSen07 | Easy | 2,093 | 145 |
lru cache | class ListNode:
def __init__(self, key=0, val=0, prev=None, next=None):
self.key = key
self.val = val
self.prev = prev
self.next = next
class LRUCache:
def __init__(self, capacity: int):
"""Initialize hash table & dll"""
self.cpty = capacity
... | https://leetcode.com/problems/lru-cache/discuss/442751/Python3-hashmap-and-doubly-linked-list | 8 | Design a data structure that follows the constraints of a Least Recently Used (LRU) cache.
Implement the LRUCache class:
LRUCache(int capacity) Initialize the LRU cache with positive size capacity.
int get(int key) Return the value of the key if the key exists, otherwise return -1.
void put(int key, int value) Update t... | [Python3] hashmap & doubly-linked list | 457 | lru-cache | 0.405 | ye15 | Medium | 2,129 | 146 |
insertion sort list | class Solution:
def insertionSortList(self, head: ListNode) -> ListNode:
# No need to sort for empty list or list of size 1
if not head or not head.next:
return head
# Use dummy_head will help us to handle insertion before head easily
dummy_head = ListNo... | https://leetcode.com/problems/insertion-sort-list/discuss/1176552/Python3-188ms-Solution-(explanation-with-visualization) | 28 | Given the head of a singly linked list, sort the list using insertion sort, and return the sorted list's head.
The steps of the insertion sort algorithm:
Insertion sort iterates, consuming one input element each repetition and growing a sorted output list.
At each iteration, insertion sort removes one element from the ... | [Python3] 188ms Solution (explanation with visualization) | 834 | insertion-sort-list | 0.503 | EckoTan0804 | Medium | 2,176 | 147 |
sort list | class Solution:
def sortList(self, head: Optional[ListNode]) -> Optional[ListNode]:
if not head or not head.next:
return head
# Split the list into two halfs
left = head
right = self.getMid(head)
tmp = right.next
right.next = None
right = ... | https://leetcode.com/problems/sort-list/discuss/1796085/Sort-List-or-Python-O(nlogn)-Solution-or-95-Faster | 25 | Given the head of a linked list, return the list after sorting it in ascending order.
Example 1:
Input: head = [4,2,1,3]
Output: [1,2,3,4]
Example 2:
Input: head = [-1,5,3,4,0]
Output: [-1,0,3,4,5]
Example 3:
Input: head = []
Output: []
Constraints:
The number of nodes in the list is in the range [0, 5 * 104].
-105... | ✔️ Sort List | Python O(nlogn) Solution | 95% Faster | 1,900 | sort-list | 0.543 | pniraj657 | Medium | 2,197 | 148 |
max points on a line | class Solution:
def maxPoints(self, points: List[List[int]]) -> int:
if len(points) <= 2:
return len(points)
def find_slope(p1, p2):
x1, y1 = p1
x2, y2 = p2
if x1-x2 == 0:
return inf
return (y1-y2)/(x1-x2)
... | https://leetcode.com/problems/max-points-on-a-line/discuss/1983010/Python-3-Using-Slopes-and-Hash-Tables-or-Clean-Python-solution | 33 | Given an array of points where points[i] = [xi, yi] represents a point on the X-Y plane, return the maximum number of points that lie on the same straight line.
Example 1:
Input: points = [[1,1],[2,2],[3,3]]
Output: 3
Example 2:
Input: points = [[1,1],[3,2],[5,3],[4,1],[2,3],[1,4]]
Output: 4
Constraints:
1 <= point... | [Python 3] Using Slopes and Hash Tables | Clean Python solution | 1,200 | max-points-on-a-line | 0.218 | hari19041 | Hard | 2,219 | 149 |
evaluate reverse polish notation | class Solution:
def evalRPN(self, tokens: List[str]) -> int:
def update(sign):
n2,n1=stack.pop(),stack.pop()
if sign=="+": return n1+n2
if sign=="-": return n1-n2
if sign=="*": return n1*n2
if sign=="/": return int(n1/n2)
stack... | https://leetcode.com/problems/evaluate-reverse-polish-notation/discuss/1732651/Super-Simple-Python-stack-solution | 6 | You are given an array of strings tokens that represents an arithmetic expression in a Reverse Polish Notation.
Evaluate the expression. Return an integer that represents the value of the expression.
Note that:
The valid operators are '+', '-', '*', and '/'.
Each operand may be an integer or another expression.
The div... | Super Simple Python 🐍 stack solution | 380 | evaluate-reverse-polish-notation | 0.441 | InjySarhan | Medium | 2,242 | 150 |
reverse words in a string | class Solution:
def reverseWords(self, s: str) -> str:
#Time: O(n) since we scan through the input, where n = len(s)
#Space: O(n)
words = []
slow, fast = 0, 0
#Use the first char to determine if we're starting on a " " or a word
mode = 'blank' if s[0] == ' ' ... | https://leetcode.com/problems/reverse-words-in-a-string/discuss/1632928/Intuitive-Two-Pointers-in-Python-without-strip()-or-split() | 10 | Given an input string s, reverse the order of the words.
A word is defined as a sequence of non-space characters. The words in s will be separated by at least one space.
Return a string of the words in reverse order concatenated by a single space.
Note that s may contain leading or trailing spaces or multiple spaces be... | Intuitive Two Pointers in Python without strip() or split() | 490 | reverse-words-in-a-string | 0.318 | surin_lovejoy | Medium | 2,290 | 151 |
maximum product subarray | class Solution:
def maxProduct(self, nums: List[int]) -> int:
curMax, curMin = 1, 1
res = nums[0]
for n in nums:
vals = (n, n * curMax, n * curMin)
curMax, curMin = max(vals), min(vals)
res = max(res, curMax)
return res | https://leetcode.com/problems/maximum-product-subarray/discuss/1608907/Python3-DYNAMIC-PROGRAMMING-Explained | 90 | Given an integer array nums, find a
subarray
that has the largest product, and return the product.
The test cases are generated so that the answer will fit in a 32-bit integer.
Example 1:
Input: nums = [2,3,-2,4]
Output: 6
Explanation: [2,3] has the largest product 6.
Example 2:
Input: nums = [-2,0,-1]
Output: 0
Expl... | ✔️[Python3] DYNAMIC PROGRAMMING, Explained | 9,700 | maximum-product-subarray | 0.349 | artod | Medium | 2,340 | 152 |
find minimum in rotated sorted array | class Solution:
def findMin(self, nums: List[int]) -> int:
start = 0
end = len(nums) - 1
if(nums[start] <= nums[end]):
return nums[0]
while start <= end:
mid = (start + end) // 2
if(nums[mid] > nums[mid+1]):
... | https://leetcode.com/problems/find-minimum-in-rotated-sorted-array/discuss/2211586/Python3-simple-naive-solution-with-binary-search | 6 | Suppose an array of length n sorted in ascending order is rotated between 1 and n times. For example, the array nums = [0,1,2,4,5,6,7] might become:
[4,5,6,7,0,1,2] if it was rotated 4 times.
[0,1,2,4,5,6,7] if it was rotated 7 times.
Notice that rotating an array [a[0], a[1], a[2], ..., a[n-1]] 1 time results in the a... | 📌 Python3 simple naive solution with binary search | 105 | find-minimum-in-rotated-sorted-array | 0.485 | Dark_wolf_jss | Medium | 2,389 | 153 |
find minimum in rotated sorted array ii | class Solution:
def findMin(self, a: List[int]) -> int:
def solve(l,h):
while l<h:
m=(l+h)//2
if a[m]<a[m-1]:
return a[m]
elif a[m]>a[h-1]:
l=m+1
... | https://leetcode.com/problems/find-minimum-in-rotated-sorted-array-ii/discuss/2087295/Binary-Search-oror-Explained-oror-PYTHON | 2 | Suppose an array of length n sorted in ascending order is rotated between 1 and n times. For example, the array nums = [0,1,4,4,5,6,7] might become:
[4,5,6,7,0,1,4] if it was rotated 4 times.
[0,1,4,4,5,6,7] if it was rotated 7 times.
Notice that rotating an array [a[0], a[1], a[2], ..., a[n-1]] 1 time results in the a... | Binary Search || Explained || PYTHON | 69 | find-minimum-in-rotated-sorted-array-ii | 0.434 | karan_8082 | Hard | 2,439 | 154 |
min stack | class MinStack:
stackWithMinElements = collections.namedtuple("stackWithMinElements", ("element", "minimum"))
def __init__(self):
self.stack : List[self.stackWithMinElements] = []
def push(self, x: int) -> None:
self.stack.append(self.stackWithMinElements(
... | https://leetcode.com/problems/min-stack/discuss/825972/Python-3-greater-91-faster-using-namedtuple | 5 | Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.
Implement the MinStack class:
MinStack() initializes the stack object.
void push(int val) pushes the element val onto the stack.
void pop() removes the element on the top of the stack.
int top() gets the top element of the... | Python 3 -> 91% faster using namedtuple | 554 | min-stack | 0.519 | mybuddy29 | Medium | 2,457 | 155 |
intersection of two linked lists | class Solution:
def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> Optional[ListNode]:
first_set=set()
curr=headA
while curr:
first_set.add(curr)
curr=curr.next
curr = headB
while curr:
if curr in first_set... | https://leetcode.com/problems/intersection-of-two-linked-lists/discuss/2116127/Python-oror-Easy-2-approaches-oror-O(1)-space | 75 | Given the heads of two singly linked-lists headA and headB, return the node at which the two lists intersect. If the two linked lists have no intersection at all, return null.
For example, the following two linked lists begin to intersect at node c1:
The test cases are generated such that there are no cycles anywhere i... | Python || Easy 2 approaches || O(1) space | 5,200 | intersection-of-two-linked-lists | 0.534 | constantine786 | Easy | 2,513 | 160 |
find peak element | class Solution:
def findPeakElement(self, lst: List[int]) -> int:
start, end = 0, len(lst) - 1
while start < end:
mid = start + (end - start) // 2
if lst[mid] > lst[mid + 1]:
end = mid
else:
start = mid + 1
return start | https://leetcode.com/problems/find-peak-element/discuss/1440424/Python-oror-Easy-Solution | 8 | A peak element is an element that is strictly greater than its neighbors.
Given a 0-indexed integer array nums, find a peak element, and return its index. If the array contains multiple peaks, return the index to any of the peaks.
You may imagine that nums[-1] = nums[n] = -∞. In other words, an element is always consid... | Python || Easy Solution | 619 | find-peak-element | 0.462 | naveenrathore | Medium | 2,545 | 162 |
maximum gap | class Solution:
def maximumGap(self, nums: List[int]) -> int:
if len(nums) == 0: return 0 #edge case
mn, mx = min(nums), max(nums)
step = max(1, (mx - mn)//(len(nums)-1)) #n-1 holes
size = (mx - mn)//step + 1
buckets = [[inf, -inf] for _ in range(size)]
for... | https://leetcode.com/problems/maximum-gap/discuss/727709/Python3-group-data-into-buckets | 6 | Given an integer array nums, return the maximum difference between two successive elements in its sorted form. If the array contains less than two elements, return 0.
You must write an algorithm that runs in linear time and uses linear extra space.
Example 1:
Input: nums = [3,6,9,1]
Output: 3
Explanation: The sorted ... | [Python3] group data into buckets | 291 | maximum-gap | 0.428 | ye15 | Hard | 2,589 | 164 |
compare version numbers | class Solution:
def compareVersion(self, v1: str, v2: str) -> int:
v1, v2 = list(map(int, v1.split('.'))), list(map(int, v2.split('.')))
for rev1, rev2 in zip_longest(v1, v2, fillvalue=0):
if rev1 == rev2:
continue
return -1 if rev1 < rev2 else 1
... | https://leetcode.com/problems/compare-version-numbers/discuss/1797594/Python3-SOLUTION-Explained | 47 | Given two version strings, version1 and version2, compare them. A version string consists of revisions separated by dots '.'. The value of the revision is its integer conversion ignoring leading zeros.
To compare version strings, compare their revision values in left-to-right order. If one of the version strings has fe... | ✔️ [Python3] SOLUTION, Explained | 3,400 | compare-version-numbers | 0.354 | artod | Medium | 2,610 | 165 |
fraction to recurring decimal | class Solution:
def fractionToDecimal(self, numerator: int, denominator: int) -> str:
if numerator % denominator == 0:
return str(numerator // denominator)
prefix = ''
if (numerator > 0) != (denominator > 0):
prefix = '-'
# Operation must be... | https://leetcode.com/problems/fraction-to-recurring-decimal/discuss/998707/Python-solution-with-detail-explanation | 3 | Given two integers representing the numerator and denominator of a fraction, return the fraction in string format.
If the fractional part is repeating, enclose the repeating part in parentheses.
If multiple answers are possible, return any of them.
It is guaranteed that the length of the answer string is less than 104 ... | Python solution with detail explanation | 650 | fraction-to-recurring-decimal | 0.241 | imasterleet | Medium | 2,647 | 166 |
two sum ii input array is sorted | class Solution:
def twoSum(self, numbers: List[int], target: int) -> List[int]:
i = 0
j = len(numbers) -1
while i<j:
s = numbers[i] + numbers[j]
if s == target:
return [i + 1 , j + 1]
if s > target:
j-=... | https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/discuss/2128459/Python-Easy-O(1)-Space | 51 | Given a 1-indexed array of integers numbers that is already sorted in non-decreasing order, find two numbers such that they add up to a specific target number. Let these two numbers be numbers[index1] and numbers[index2] where 1 <= index1 < index2 <= numbers.length.
Return the indices of the two numbers, index1 and ind... | Python Easy O(1) Space | 3,700 | two-sum-ii-input-array-is-sorted | 0.6 | constantine786 | Medium | 2,656 | 167 |
excel sheet column title | class Solution(object):
def convertToTitle(self, columnNumber):
# Create an empty string for storing the characters...
output = ""
# Run a while loop while columnNumber is positive...
while columnNumber > 0:
# Subtract 1 from columnNumber and get current character by doin... | https://leetcode.com/problems/excel-sheet-column-title/discuss/2448578/Easy-oror-0-ms-oror-100-oror-Fully-Explained-(Java-C%2B%2B-Python-Python3) | 22 | Given an integer columnNumber, return its corresponding column title as it appears in an Excel sheet.
For example:
A -> 1
B -> 2
C -> 3
...
Z -> 26
AA -> 27
AB -> 28
...
Example 1:
Input: columnNumber = 1
Output: "A"
Example 2:
Input: columnNumber = 28
Output: "AB"
Example 3:
Input: columnNumber = 701
Output: "ZY"
... | Easy || 0 ms || 100% || Fully Explained (Java, C++, Python, Python3) | 1,300 | excel-sheet-column-title | 0.348 | PratikSen07 | Easy | 2,709 | 168 |
majority element | class Solution:
def majorityElement(self, nums: List[int]) -> int:
curr, count = nums[0], 1 # curr will store the current majority element, count will store the count of the majority
for i in range(1,len(nums)):
count += (1 if curr == nums[i] else -1) # if i is equal to c... | https://leetcode.com/problems/majority-element/discuss/1788112/Python-easy-solution-O(n)-or-O(1)-or-explained | 18 | Given an array nums of size n, return the majority element.
The majority element is the element that appears more than ⌊n / 2⌋ times. You may assume that the majority element always exists in the array.
Example 1:
Input: nums = [3,2,3]
Output: 3
Example 2:
Input: nums = [2,2,1,1,1,2,2]
Output: 2
Constraints:
n == n... | ✅ Python easy solution O(n) | O(1) | explained | 1,700 | majority-element | 0.639 | dhananjay79 | Easy | 2,746 | 169 |
excel sheet column number | class Solution:
def titleToNumber(self, columnTitle: str) -> int:
ans, pos = 0, 0
for letter in reversed(columnTitle):
digit = ord(letter)-64
ans += digit * 26**pos
pos += 1
return ans | https://leetcode.com/problems/excel-sheet-column-number/discuss/1790567/Python3-CLEAN-SOLUTION-()-Explained | 105 | Given a string columnTitle that represents the column title as appears in an Excel sheet, return its corresponding column number.
For example:
A -> 1
B -> 2
C -> 3
...
Z -> 26
AA -> 27
AB -> 28
...
Example 1:
Input: columnTitle = "A"
Output: 1
Example 2:
Input: columnTitle = "AB"
Output: 28
Example 3:
Input: columnT... | ✔️ [Python3] CLEAN SOLUTION (๑❛ꆚ❛๑), Explained | 8,500 | excel-sheet-column-number | 0.614 | artod | Easy | 2,793 | 171 |
factorial trailing zeroes | class Solution:
def trailingZeroes(self, n: int) -> int:
quotient = n // 5
return quotient + self.trailingZeroes(quotient) if quotient >= 5 else quotient | https://leetcode.com/problems/factorial-trailing-zeroes/discuss/1152167/Python3-O(log(n))-time-O(1)-space.-Explanation | 12 | Given an integer n, return the number of trailing zeroes in n!.
Note that n! = n * (n - 1) * (n - 2) * ... * 3 * 2 * 1.
Example 1:
Input: n = 3
Output: 0
Explanation: 3! = 6, no trailing zero.
Example 2:
Input: n = 5
Output: 1
Explanation: 5! = 120, one trailing zero.
Example 3:
Input: n = 0
Output: 0
Constraints:
... | Python3 O(log(n)) time, O(1) space. Explanation | 472 | factorial-trailing-zeroes | 0.418 | ryancodrai | Medium | 2,851 | 172 |
binary search tree iterator | class BSTIterator:
def __init__(self, root: Optional[TreeNode]):
self.iter = self._inorder(root)
self.nxt = next(self.iter, None)
def _inorder(self, node: Optional[TreeNode]) -> Generator[int, None, None]:
if node:
yield from self._inorder(node.left)
yield no... | https://leetcode.com/problems/binary-search-tree-iterator/discuss/1965156/Python-TC-O(1)-SC-O(h)-Generator-Solution | 34 | Implement the BSTIterator class that represents an iterator over the in-order traversal of a binary search tree (BST):
BSTIterator(TreeNode root) Initializes an object of the BSTIterator class. The root of the BST is given as part of the constructor. The pointer should be initialized to a non-existent number smaller th... | [Python] TC O(1) SC O(h) Generator Solution | 2,300 | binary-search-tree-iterator | 0.692 | zayne-siew | Medium | 2,878 | 173 |
dungeon game | class Solution:
def calculateMinimumHP(self, dungeon: List[List[int]]) -> int:
m, n = len(dungeon), len(dungeon[0])
@cache
def fn(i, j):
"""Return min health at (i,j)."""
if i == m or j == n: return inf
if i == m-1 and j == n-1: return max(1, 1 - ... | https://leetcode.com/problems/dungeon-game/discuss/699433/Python3-dp | 1 | The demons had captured the princess and imprisoned her in the bottom-right corner of a dungeon. The dungeon consists of m x n rooms laid out in a 2D grid. Our valiant knight was initially positioned in the top-left room and must fight his way through dungeon to rescue the princess.
The knight has an initial health poi... | [Python3] dp | 45 | dungeon-game | 0.373 | ye15 | Hard | 2,911 | 174 |
largest number | class Solution:
def largestNumber(self, nums: List[int]) -> str:
nums = sorted(nums,key=lambda x:x / (10 ** len(str(x)) - 1 ), reverse=True)
str_nums = [str(num) for num in nums]
res = ''.join(str_nums)
res = str(int(res))
return res | https://leetcode.com/problems/largest-number/discuss/1391073/python-easy-custom-sort-solution!!!!!!! | 9 | Given a list of non-negative integers nums, arrange them such that they form the largest number and return it.
Since the result may be very large, so you need to return a string instead of an integer.
Example 1:
Input: nums = [10,2]
Output: "210"
Example 2:
Input: nums = [3,30,34,5,9]
Output: "9534330"
Constraints:... | python easy custom sort solution!!!!!!! | 900 | largest-number | 0.341 | user0665m | Medium | 2,928 | 179 |
repeated dna sequences | class Solution:
def findRepeatedDnaSequences(self, s: str) -> List[str]:
res, d = [], {}
for i in range(len(s)):
if s[i:i+10] not in d: d[s[i:i+10]] = 0
elif s[i:i+10] not in res: res.append(s[i:i+10])
return res
# An Upvote... | https://leetcode.com/problems/repeated-dna-sequences/discuss/2223482/Simple-Python-Solution-oror-O(n)-Time-oror-O(n)-Space-oror-Sliding-Window | 2 | The DNA sequence is composed of a series of nucleotides abbreviated as 'A', 'C', 'G', and 'T'.
For example, "ACGAATTCCG" is a DNA sequence.
When studying DNA, it is useful to identify repeated sequences within the DNA.
Given a string s that represents a DNA sequence, return all the 10-letter-long sequences (substrings)... | Simple Python Solution || O(n) Time || O(n) Space || Sliding Window | 121 | repeated-dna-sequences | 0.463 | rajkumarerrakutti | Medium | 2,949 | 187 |
best time to buy and sell stock iv | class Solution:
def maxProfit(self, k: int, prices: List[int]) -> int:
# no transaction, no profit
if k == 0: return 0
# dp[k][0] = min cost you need to spend at most k transactions
# dp[k][1] = max profit you can achieve at most k transactions
dp = [[1000, 0] for _ in range(... | https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iv/discuss/2555699/LeetCode-The-Hard-Way-7-Lines-or-Line-By-Line-Explanation | 62 | You are given an integer array prices where prices[i] is the price of a given stock on the ith day, and an integer k.
Find the maximum profit you can achieve. You may complete at most k transactions: i.e. you may buy at most k times and sell at most k times.
Note: You may not engage in multiple transactions simultaneou... | 🔥 [LeetCode The Hard Way] 🔥 7 Lines | Line By Line Explanation | 3,600 | best-time-to-buy-and-sell-stock-iv | 0.381 | wingkwong | Hard | 2,969 | 188 |
rotate array | class Solution:
def rotate(self, nums: List[int], k: int) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
def twopt(arr, i, j):
while (i < j):
arr[i], arr[j] = arr[j], arr[i]
i += 1
j -= 1... | https://leetcode.com/problems/rotate-array/discuss/1419527/Python-or-Two-Pointers-solution | 31 | Given an integer array nums, rotate the array to the right by k steps, where k is non-negative.
Example 1:
Input: nums = [1,2,3,4,5,6,7], k = 3
Output: [5,6,7,1,2,3,4]
Explanation:
rotate 1 steps to the right: [7,1,2,3,4,5,6]
rotate 2 steps to the right: [6,7,1,2,3,4,5]
rotate 3 steps to the right: [5,6,7,1,2,3,4]
Ex... | Python | Two-Pointers solution | 3,900 | rotate-array | 0.392 | Shreya19595 | Medium | 3,000 | 189 |
reverse bits | class Solution:
def reverseBits(self, n: int) -> int:
res = 0
for _ in range(32):
res = (res<<1) + (n&1)
n>>=1
return res | https://leetcode.com/problems/reverse-bits/discuss/1791099/Python-3-(40ms)-or-Real-BIT-Manipulation-Solution | 22 | Reverse bits of a given 32 bits unsigned integer.
Note:
Note that in some languages, such as Java, there is no unsigned integer type. In this case, both input and output will be given as a signed integer type. They should not affect your implementation, as the integer's internal binary representation is the same, wheth... | Python 3 (40ms) | Real BIT Manipulation Solution | 1,800 | reverse-bits | 0.525 | MrShobhit | Easy | 3,053 | 190 |
number of 1 bits | class Solution:
def hammingWeight(self, n: int) -> int:
return sum((n & (1<<i))!=0 for i in range(32)) | https://leetcode.com/problems/number-of-1-bits/discuss/2074152/Easy-O(1)-Space-PythonC%2B%2B | 21 | Write a function that takes the binary representation of a positive integer and returns the number of
set bits
it has (also known as the Hamming weight).
Example 1:
Input: n = 11
Output: 3
Explanation:
The input binary string 1011 has a total of three set bits.
Example 2:
Input: n = 128
Output: 1
Explanation:
The inp... | Easy O(1) Space - Python/C++ | 2,800 | number-of-1-bits | 0.65 | constantine786 | Easy | 3,104 | 191 |
house robber | class Solution:
def __init__(self):
self.cache = {}
def rob_rec(self, nums, start):
if start >= len(nums):
return 0
if start in self.cache:
return self.cache[start]
self.cache[start] = nums[start] + max(self.rob_rec(nums, start+2... | https://leetcode.com/problems/house-robber/discuss/378700/Python-multiple-solutions | 23 | You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed, the only constraint stopping you from robbing each of them is that adjacent houses have security systems connected and it will automatically contact the police if two adjacent houses were broken into o... | Python multiple solutions | 2,500 | house-robber | 0.488 | amchoukir | Medium | 3,149 | 198 |
binary tree right side view | class Solution:
def rightSideView(self, root: Optional[TreeNode]) -> List[int]:
def solve(root, lvl):
if root:
if len(res)==lvl:
res.append(root.val)
solve(root.right, lvl + 1)
solve(root.left, lvl + 1)
return
res = []
sol... | https://leetcode.com/problems/binary-tree-right-side-view/discuss/2266055/C%2B%2B-oror-PYTHON-oror-EXPLAINED-oror | 80 | Given the root of a binary tree, imagine yourself standing on the right side of it, return the values of the nodes you can see ordered from top to bottom.
Example 1:
Input: root = [1,2,3,null,5,null,4]
Output: [1,3,4]
Example 2:
Input: root = [1,null,3]
Output: [1,3]
Example 3:
Input: root = []
Output: []
Constrain... | ✔️ C++ || PYTHON || EXPLAINED || ; ] | 4,400 | binary-tree-right-side-view | 0.612 | karan_8082 | Medium | 3,210 | 199 |
number of islands | class Solution:
def numIslands(self, grid: List[List[str]]) -> int:
if not grid: return 0
m, n = len(grid), len(grid[0])
ans = 0
def dfs(i, j):
grid[i][j] = '2'
for di, dj in (0, 1), (0, -1), (1, 0), (-1, 0):
ii, jj = i+di, j+dj
... | https://leetcode.com/problems/number-of-islands/discuss/863366/Python-3-or-DFS-BFS-Union-Find-All-3-methods-or-Explanation | 50 | Given an m x n 2D binary grid grid which represents a map of '1's (land) and '0's (water), return the number of islands.
An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water.
Example 1:
Input: grid... | Python 3 | DFS, BFS, Union Find, All 3 methods | Explanation | 5,200 | number-of-islands | 0.564 | idontknoooo | Medium | 3,235 | 200 |
bitwise and of numbers range | class Solution:
def rangeBitwiseAnd(self, m: int, n: int) -> int:
shift = 0
# find the common MSB bits.
while m != n:
m = m >> 1
n = n >> 1
shift += 1
return m << shift | https://leetcode.com/problems/bitwise-and-of-numbers-range/discuss/469130/Python-iterative-sol.-based-on-bit-manipulation | 9 | Given two integers left and right that represent the range [left, right], return the bitwise AND of all numbers in this range, inclusive.
Example 1:
Input: left = 5, right = 7
Output: 4
Example 2:
Input: left = 0, right = 0
Output: 0
Example 3:
Input: left = 1, right = 2147483647
Output: 0
Constraints:
0 <= left <=... | Python iterative sol. based on bit-manipulation | 723 | bitwise-and-of-numbers-range | 0.423 | brianchiang_tw | Medium | 3,287 | 201 |
happy number | class Solution(object):
def isHappy(self, n):
hset = set()
while n != 1:
if n in hset: return False
hset.add(n)
n = sum([int(i) ** 2 for i in str(n)])
else:
return True | https://leetcode.com/problems/happy-number/discuss/2383810/Very-Easy-0-ms-100(Fully-Explained)(C%2B%2B-Java-Python-JS-C-Python3) | 18 | Write an algorithm to determine if a number n is happy.
A happy number is a number defined by the following process:
Starting with any positive integer, replace the number by the sum of the squares of its digits.
Repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which d... | Very Easy 0 ms 100%(Fully Explained)(C++, Java, Python, JS, C, Python3) | 1,700 | happy-number | 0.545 | PratikSen07 | Easy | 3,301 | 202 |
remove linked list elements | class Solution:
def removeElements(self, head, val):
"""
:type head: ListNode
:type val: int
:rtype: ListNode
"""
dummy_head = ListNode(-1)
dummy_head.next = head
current_node = dummy_head
while current_node.next != None:
... | https://leetcode.com/problems/remove-linked-list-elements/discuss/158651/Simple-Python-solution-with-explanation-(single-pointer-dummy-head). | 429 | Given the head of a linked list and an integer val, remove all the nodes of the linked list that has Node.val == val, and return the new head.
Example 1:
Input: head = [1,2,6,3,4,5,6], val = 6
Output: [1,2,3,4,5]
Example 2:
Input: head = [], val = 1
Output: []
Example 3:
Input: head = [7,7,7,7], val = 7
Output: []
... | Simple Python solution with explanation (single pointer, dummy head). | 28,900 | remove-linked-list-elements | 0.449 | Hai_dee | Easy | 3,349 | 203 |
count primes | class Solution:
def countPrimes(self, n: int) -> int:
if n<2:
return 0
#initialize a list of length n
prime=[1]*n
#mark 0th and 1st index as 0
prime[0]=prime[1]=0
#we will check for multiple from range 2 to sqrt(n)
for i in range(2,... | https://leetcode.com/problems/count-primes/discuss/1267254/Python-3-solution-97.7-faster | 11 | Given an integer n, return the number of prime numbers that are strictly less than n.
Example 1:
Input: n = 10
Output: 4
Explanation: There are 4 prime numbers less than 10, they are 2, 3, 5, 7.
Example 2:
Input: n = 0
Output: 0
Example 3:
Input: n = 1
Output: 0
Constraints:
0 <= n <= 5 * 106 | Python 3 solution 97.7% faster | 1,700 | count-primes | 0.331 | ritesh98 | Medium | 3,375 | 204 |
isomorphic strings | class Solution:
def isIsomorphic(self, s: str, t: str) -> bool:
return [*map(s.index, s)] == [*map(t.index, t)] | https://leetcode.com/problems/isomorphic-strings/discuss/2472118/Very-Easy-oror-100-oror-Fully-Explained-oror-Java-C%2B%2B-Python-Javascript-Python3-(Using-HashMap) | 44 | Given two strings s and t, determine if they are isomorphic.
Two strings s and t are isomorphic if the characters in s can be replaced to get t.
All occurrences of a character must be replaced with another character while preserving the order of characters. No two characters may map to the same character, but a charact... | Very Easy || 100% || Fully Explained || Java, C++, Python, Javascript, Python3 (Using HashMap) | 5,500 | isomorphic-strings | 0.426 | PratikSen07 | Easy | 3,395 | 205 |
reverse linked list | class Solution(object):
def reverseList(self, head):
# Initialize prev pointer as NULL...
prev = None
# Initialize the curr pointer as the head...
curr = head
# Run a loop till curr points to NULL...
while curr:
# Initialize next pointer as the next pointe... | https://leetcode.com/problems/reverse-linked-list/discuss/2458632/Easy-oror-0-ms-oror-100-oror-Fully-Explained-oror-Java-C%2B%2B-Python-JS-C-Python3-(Recursive-and-Iterative) | 92 | Given the head of a singly linked list, reverse the list, and return the reversed list.
Example 1:
Input: head = [1,2,3,4,5]
Output: [5,4,3,2,1]
Example 2:
Input: head = [1,2]
Output: [2,1]
Example 3:
Input: head = []
Output: []
Constraints:
The number of nodes in the list is the range [0, 5000].
-5000 <= Node.val ... | Easy || 0 ms || 100% || Fully Explained || Java, C++, Python, JS, C, Python3 (Recursive & Iterative) | 6,800 | reverse-linked-list | 0.726 | PratikSen07 | Easy | 3,451 | 206 |
course schedule | class Solution:
def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool:
graph=defaultdict(list)
indegree={}
#initialising dictionary
for i in range(numCourses):
indegree[i]=0
#filling graph and indegree dictionaries
for child,parent in prerequisites:
graph[parent].append(chil... | https://leetcode.com/problems/course-schedule/discuss/1627381/Simple-and-Easy-Topological-Sorting-code-beats-97.63-python-submissions | 11 | There are a total of numCourses courses you have to take, labeled from 0 to numCourses - 1. You are given an array prerequisites where prerequisites[i] = [ai, bi] indicates that you must take course bi first if you want to take course ai.
For example, the pair [0, 1], indicates that to take course 0 you have to first t... | Simple and Easy Topological Sorting code, beats 97.63% python submissions | 1,400 | course-schedule | 0.454 | RaghavGupta22 | Medium | 3,483 | 207 |
minimum size subarray sum | class Solution:
def minSubArrayLen(self, target: int, nums: List[int]) -> int:
left = 0 # keep track of left pointer
rsum = 0 # keep the running sum
res = None # Answer we will return
# Iterate through the array, the index will be your right pointer
for righ... | https://leetcode.com/problems/minimum-size-subarray-sum/discuss/1774062/Python-Explanation-of-sliding-window-using-comments | 8 | Given an array of positive integers nums and a positive integer target, return the minimal length of a
subarray
whose sum is greater than or equal to target. If there is no such subarray, return 0 instead.
Example 1:
Input: target = 7, nums = [2,3,1,2,4,3]
Output: 2
Explanation: The subarray [4,3] has the minimal len... | Python - Explanation of sliding window using comments | 376 | minimum-size-subarray-sum | 0.445 | iamricks | Medium | 3,530 | 209 |
course schedule ii | class Solution:
def findOrder(self, numCourses: int, prerequisites: List[List[int]]) -> List[int]:
# Handle edge case.
if not prerequisites: return [course for course in range(numCourses)]
# 'parents' maps each course to a list of its pre
# -requisites.
parents = ... | https://leetcode.com/problems/course-schedule-ii/discuss/1327646/Elegant-Python-DFS | 4 | There are a total of numCourses courses you have to take, labeled from 0 to numCourses - 1. You are given an array prerequisites where prerequisites[i] = [ai, bi] indicates that you must take course bi first if you want to take course ai.
For example, the pair [0, 1], indicates that to take course 0 you have to first t... | Elegant Python DFS | 467 | course-schedule-ii | 0.481 | soma28 | Medium | 3,580 | 210 |
word search ii | class Solution:
def findWords(self, board: List[List[str]], words: List[str]) -> List[str]:
m = len(board)
n = len(board[0])
res = []
d = [[0, 1], [0, -1], [1, 0], [-1, 0]]
ref = set()
for i in range(m):
for j in range(n-1):
ref.add(board... | https://leetcode.com/problems/word-search-ii/discuss/2351408/python3-solution-oror-99-more-faster-oror-39-ms | 3 | Given an m x n board of characters and a list of strings words, return all words on the board.
Each word must be constructed from letters of sequentially adjacent cells, where adjacent cells are horizontally or vertically neighboring. The same letter cell may not be used more than once in a word.
Example 1:
Input: bo... | python3 solution || 99% more faster || 39 ms | 301 | word-search-ii | 0.368 | vimla_kushwaha | Hard | 3,627 | 212 |
house robber ii | class Solution:
def rob(self, nums: List[int]) -> int:
if len(nums) == 1:
return nums[0]
dp = {}
def getResult(a,i):
if i>=len(a):
return 0
if i in dp:
return dp[i]
sum = 0
... | https://leetcode.com/problems/house-robber-ii/discuss/2158878/Do-house-robber-twice | 4 | You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed. All houses at this place are arranged in a circle. That means the first house is the neighbor of the last one. Meanwhile, adjacent houses have a security system connected, and it will automatically con... | 📌 Do house robber twice | 104 | house-robber-ii | 0.407 | Dark_wolf_jss | Medium | 3,648 | 213 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.