The first 30 problems of https://leetcode.com/problemset/ (default view), in order.
How to use: open a problem in LeetCode, make sure the language is Python 3,
select all in the editor (Ctrl/Cmd + A), paste the matching code block below, and submit.
Verified locally: every solution was checked against the problem's official examples,
edge cases, and randomized brute-force cross-checks, including worst-case sizes.
| # | Problem | Difficulty |
|---|---|---|
| 1 | Two Sum | Easy |
| 2 | Add Two Numbers | Medium |
| 3 | Longest Substring Without Repeating Characters | Medium |
| 4 | Median of Two Sorted Arrays | Hard |
| 5 | Longest Palindromic Substring | Medium |
| 6 | Zigzag Conversion | Medium |
| 7 | Reverse Integer | Medium |
| 8 | String to Integer (atoi) | Medium |
| 9 | Palindrome Number | Easy |
| 10 | Regular Expression Matching | Hard |
| 11 | Container With Most Water | Medium |
| 12 | Integer to Roman | Medium |
| 13 | Roman to Integer | Easy |
| 14 | Longest Common Prefix | Easy |
| 15 | 3Sum | Medium |
| 16 | 3Sum Closest | Medium |
| 17 | Letter Combinations of a Phone Number | Medium |
| 18 | 4Sum | Medium |
| 19 | Remove Nth Node From End of List | Medium |
| 20 | Valid Parentheses | Easy |
| 21 | Merge Two Sorted Lists | Easy |
| 22 | Generate Parentheses | Medium |
| 23 | Merge k Sorted Lists | Hard |
| 24 | Swap Nodes in Pairs | Medium |
| 25 | Reverse Nodes in k-Group | Hard |
| 26 | Remove Duplicates from Sorted Array | Easy |
| 27 | Remove Element | Easy |
| 28 | Find the Index of the First Occurrence in a String | Easy |
| 29 | Divide Two Integers | Medium |
| 30 | Substring with Concatenation of All Words | Hard |
1. Two Sum (Easy)
https://leetcode.com/problems/two-sum/
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
seen = {}
for i, num in enumerate(nums):
comp = target - num
if comp in seen:
return [seen[comp], i]
seen[num] = i
2. Add Two Numbers (Medium)
https://leetcode.com/problems/add-two-numbers/
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:
dummy = ListNode()
cur = dummy
carry = 0
while l1 or l2:
total = carry
if l1:
total += l1.val
l1 = l1.next
if l2:
total += l2.val
l2 = l2.next
carry, digit = divmod(total, 10)
cur.next = ListNode(digit)
cur = cur.next
if carry:
cur.next = ListNode(carry)
return dummy.next
3. Longest Substring Without Repeating Characters (Medium)
https://leetcode.com/problems/longest-substring-without-repeating-characters/
class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
last = {}
start = best = 0
for i, ch in enumerate(s):
if ch in last and last[ch] >= start:
start = last[ch] + 1
last[ch] = i
best = max(best, i - start + 1)
return best
4. Median of Two Sorted Arrays (Hard)
https://leetcode.com/problems/median-of-two-sorted-arrays/
class Solution:
def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float:
if len(nums1) > len(nums2):
nums1, nums2 = nums2, nums1
m, n = len(nums1), len(nums2)
lo, hi = 0, m
half = (m + n + 1) // 2
while lo <= hi:
i = (lo + hi) // 2
j = half - i
l1 = nums1[i - 1] if i > 0 else float("-inf")
r1 = nums1[i] if i < m else float("inf")
l2 = nums2[j - 1] if j > 0 else float("-inf")
r2 = nums2[j] if j < n else float("inf")
if l1 <= r2 and l2 <= r1:
if (m + n) % 2 == 1:
return float(max(l1, l2))
return (max(l1, l2) + min(r1, r2)) / 2.0
if l1 > r2:
hi = i - 1
else:
lo = i + 1
5. Longest Palindromic Substring (Medium)
https://leetcode.com/problems/longest-palindromic-substring/
class Solution:
def longestPalindrome(self, s: str) -> str:
# Manacher's algorithm, O(n)
t = "#" + "#".join(s) + "#"
n = len(t)
p = [0] * n
c = r = 0
for i in range(n):
if i < r:
p[i] = min(r - i, p[2 * c - i])
while i - p[i] - 1 >= 0 and i + p[i] + 1 < n and t[i - p[i] - 1] == t[i + p[i] + 1]:
p[i] += 1
if i + p[i] > r:
c, r = i, i + p[i]
best = max(p)
center = p.index(best)
start = (center - best) // 2
return s[start:start + best]
6. Zigzag Conversion (Medium)
https://leetcode.com/problems/zigzag-conversion/
class Solution:
def convert(self, s: str, numRows: int) -> str:
if numRows == 1 or numRows >= len(s):
return s
rows = [""] * numRows
row = 0
step = 1
for ch in s:
rows[row] += ch
if row == 0:
step = 1
elif row == numRows - 1:
step = -1
row += step
return "".join(rows)
7. Reverse Integer (Medium)
https://leetcode.com/problems/reverse-integer/
class Solution:
def reverse(self, x: int) -> int:
sign = -1 if x < 0 else 1
rev = int(str(abs(x))[::-1]) * sign
return rev if -2 ** 31 <= rev <= 2 ** 31 - 1 else 0
8. String to Integer (atoi) (Medium)
https://leetcode.com/problems/string-to-integer-atoi/
class Solution:
def myAtoi(self, s: str) -> int:
s = s.strip()
if not s:
return 0
sign = 1
i = 0
if s[0] == "+" or s[0] == "-":
if s[0] == "-":
sign = -1
i = 1
num = 0
for ch in s[i:]:
if "0" <= ch <= "9":
num = num * 10 + (ord(ch) - 48)
else:
break
res = sign * num
if res > 2 ** 31 - 1:
return 2 ** 31 - 1
if res < -2 ** 31:
return -2 ** 31
return res
9. Palindrome Number (Easy)
https://leetcode.com/problems/palindrome-number/
class Solution:
def isPalindrome(self, x: int) -> bool:
if x < 0 or (x % 10 == 0 and x != 0):
return False
rev = 0
while x > rev:
rev = rev * 10 + x % 10
x //= 10
return x == rev or x == rev // 10
10. Regular Expression Matching (Hard)
https://leetcode.com/problems/regular-expression-matching/
class Solution:
def isMatch(self, s: str, p: str) -> bool:
m, n = len(s), len(p)
dp = [[False] * (n + 1) for _ in range(m + 1)]
dp[0][0] = True
for j in range(2, n + 1):
if p[j - 1] == "*":
dp[0][j] = dp[0][j - 2]
for i in range(1, m + 1):
for j in range(1, n + 1):
if p[j - 1] == "*":
dp[i][j] = dp[i][j - 2]
if p[j - 2] == s[i - 1] or p[j - 2] == ".":
dp[i][j] = dp[i][j] or dp[i - 1][j]
else:
dp[i][j] = dp[i - 1][j - 1] and (p[j - 1] == s[i - 1] or p[j - 1] == ".")
return dp[m][n]
11. Container With Most Water (Medium)
https://leetcode.com/problems/container-with-most-water/
class Solution:
def maxArea(self, height: List[int]) -> int:
l, r = 0, len(height) - 1
best = 0
while l < r:
best = max(best, (r - l) * min(height[l], height[r]))
if height[l] < height[r]:
l += 1
else:
r -= 1
return best
12. Integer to Roman (Medium)
https://leetcode.com/problems/integer-to-roman/
class Solution:
def intToRoman(self, num: int) -> str:
vals = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1]
syms = ["M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"]
res = []
for v, sym in zip(vals, syms):
while num >= v:
res.append(sym)
num -= v
return "".join(res)
13. Roman to Integer (Easy)
https://leetcode.com/problems/roman-to-integer/
class Solution:
def romanToInt(self, s: str) -> int:
val = {"I": 1, "V": 5, "X": 10, "L": 50, "C": 100, "D": 500, "M": 1000}
total = 0
for i, ch in enumerate(s):
if i + 1 < len(s) and val[ch] < val[s[i + 1]]:
total -= val[ch]
else:
total += val[ch]
return total
14. Longest Common Prefix (Easy)
https://leetcode.com/problems/longest-common-prefix/
class Solution:
def longestCommonPrefix(self, strs: List[str]) -> str:
if not strs:
return ""
res = ""
for i, ch in enumerate(strs[0]):
for s in strs[1:]:
if i >= len(s) or s[i] != ch:
return res
res += ch
return res
15. 3Sum (Medium)
https://leetcode.com/problems/3sum/
class Solution:
def threeSum(self, nums: list[int]) -> list[list[int]]:
nums.sort()
n = len(nums)
res = []
for i in range(n - 2):
if i > 0 and nums[i] == nums[i - 1]:
continue
l, r = i + 1, n - 1
while l < r:
total = nums[i] + nums[l] + nums[r]
if total == 0:
res.append([nums[i], nums[l], nums[r]])
while l < r and nums[l] == nums[l + 1]:
l += 1
while l < r and nums[r] == nums[r - 1]:
r -= 1
l += 1
r -= 1
elif total < 0:
l += 1
else:
r -= 1
return res
16. 3Sum Closest (Medium)
https://leetcode.com/problems/3sum-closest/
class Solution:
def threeSumClosest(self, nums: List[int], target: int) -> int:
nums.sort()
n = len(nums)
best = nums[0] + nums[1] + nums[2]
for i in range(n - 2):
l, r = i + 1, n - 1
while l < r:
total = nums[i] + nums[l] + nums[r]
if abs(total - target) < abs(best - target):
best = total
if total < target:
l += 1
elif total > target:
r -= 1
else:
return target
return best
17. Letter Combinations of a Phone Number (Medium)
https://leetcode.com/problems/letter-combinations-of-a-phone-number/
class Solution:
def letterCombinations(self, digits: str) -> List[str]:
if not digits:
return []
phone = {
"2": "abc", "3": "def", "4": "ghi", "5": "jkl",
"6": "mno", "7": "pqrs", "8": "tuv", "9": "wxyz",
}
res = [""]
for d in digits:
res = [prefix + c for prefix in res for c in phone[d]]
return res
18. 4Sum (Medium)
https://leetcode.com/problems/4sum/
class Solution:
def fourSum(self, nums: List[int], target: int) -> List[List[int]]:
nums.sort()
n = len(nums)
res = []
for i in range(n - 3):
if i > 0 and nums[i] == nums[i - 1]:
continue
for j in range(i + 1, n - 2):
if j > i + 1 and nums[j] == nums[j - 1]:
continue
l, r = j + 1, n - 1
while l < r:
total = nums[i] + nums[j] + nums[l] + nums[r]
if total == target:
res.append([nums[i], nums[j], nums[l], nums[r]])
while l < r and nums[l] == nums[l + 1]:
l += 1
while l < r and nums[r] == nums[r - 1]:
r -= 1
l += 1
r -= 1
elif total < target:
l += 1
else:
r -= 1
return res
19. Remove Nth Node From End of List (Medium)
https://leetcode.com/problems/remove-nth-node-from-end-of-list/
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]:
dummy = ListNode(0, head)
fast = slow = dummy
for _ in range(n):
fast = fast.next
while fast.next:
fast = fast.next
slow = slow.next
slow.next = slow.next.next
return dummy.next
20. Valid Parentheses (Easy)
https://leetcode.com/problems/valid-parentheses/
class Solution:
def isValid(self, s: str) -> bool:
stack = []
pairs = {")": "(", "]": "[", "}": "{"}
for ch in s:
if ch in pairs:
if not stack or stack[-1] != pairs[ch]:
return False
stack.pop()
else:
stack.append(ch)
return not stack
21. Merge Two Sorted Lists (Easy)
https://leetcode.com/problems/merge-two-sorted-lists/
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]:
dummy = ListNode()
cur = dummy
while list1 and list2:
if list1.val <= list2.val:
cur.next = list1
list1 = list1.next
else:
cur.next = list2
list2 = list2.next
cur = cur.next
cur.next = list1 if list1 else list2
return dummy.next
22. Generate Parentheses (Medium)
https://leetcode.com/problems/generate-parentheses/
class Solution:
def generateParenthesis(self, n: int) -> List[str]:
res = []
def backtrack(cur, open_count, close_count):
if len(cur) == 2 * n:
res.append(cur)
return
if open_count < n:
backtrack(cur + "(", open_count + 1, close_count)
if close_count < open_count:
backtrack(cur + ")", open_count, close_count + 1)
backtrack("", 0, 0)
return res
23. Merge k Sorted Lists (Hard)
https://leetcode.com/problems/merge-k-sorted-lists/
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def mergeKLists(self, lists: List[Optional[ListNode]]) -> Optional[ListNode]:
import heapq
dummy = ListNode()
cur = dummy
heap = []
for i, node in enumerate(lists):
if node:
heapq.heappush(heap, (node.val, i, node))
tie = len(lists)
while heap:
_, _, node = heapq.heappop(heap)
cur.next = node
cur = cur.next
if node.next:
heapq.heappush(heap, (node.next.val, tie, node.next))
tie += 1
return dummy.next
24. Swap Nodes in Pairs (Medium)
https://leetcode.com/problems/swap-nodes-in-pairs/
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def swapPairs(self, head: Optional[ListNode]) -> Optional[ListNode]:
dummy = ListNode(0, head)
prev = dummy
while prev.next and prev.next.next:
first = prev.next
second = first.next
first.next = second.next
second.next = first
prev.next = second
prev = first
return dummy.next
25. Reverse Nodes in k-Group (Hard)
https://leetcode.com/problems/reverse-nodes-in-k-group/
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def reverseKGroup(self, head: Optional[ListNode], k: int) -> Optional[ListNode]:
dummy = ListNode(0, head)
prev = dummy
while True:
kth = prev
for _ in range(k):
kth = kth.next
if kth is None:
return dummy.next
group_head = prev.next
kth_next = kth.next
curr = group_head
nxt = curr.next
for _ in range(k - 1):
nxt_next = nxt.next
nxt.next = curr
curr = nxt
nxt = nxt_next
group_head.next = kth_next
prev.next = curr
prev = group_head
26. Remove Duplicates from Sorted Array (Easy)
https://leetcode.com/problems/remove-duplicates-from-sorted-array/
class Solution:
def removeDuplicates(self, nums: List[int]) -> int:
if not nums:
return 0
write = 1
for x in nums[1:]:
if x != nums[write - 1]:
nums[write] = x
write += 1
return write
27. Remove Element (Easy)
https://leetcode.com/problems/remove-element/
class Solution:
def removeElement(self, nums: List[int], val: int) -> int:
write = 0
for x in nums:
if x != val:
nums[write] = x
write += 1
return write
28. Find the Index of the First Occurrence in a String (Easy)
https://leetcode.com/problems/find-the-index-of-the-first-occurrence-in-a-string/
class Solution:
def strStr(self, haystack: str, needle: str) -> int:
return haystack.find(needle)
29. Divide Two Integers (Medium)
https://leetcode.com/problems/divide-two-integers/
class Solution:
def divide(self, dividend: int, divisor: int) -> int:
INT_MIN, INT_MAX = -2 ** 31, 2 ** 31 - 1
if dividend == 0:
return 0
if divisor == 1:
return dividend
if divisor == -1:
return INT_MAX if dividend == INT_MIN else -dividend
negative = (dividend < 0) ^ (divisor < 0)
a, b = abs(dividend), abs(divisor)
result = 0
while a >= b:
shift = 0
while a >= (b << (shift + 1)):
shift += 1
result += 1 << shift
a -= b << shift
return -result if negative else result
30. Substring with Concatenation of All Words (Hard)
https://leetcode.com/problems/substring-with-concatenation-of-all-words/
class Solution:
def findSubstring(self, s: str, words: List[str]) -> List[int]:
from collections import Counter
n, m = len(s), len(words)
if m == 0:
return []
word_len = len(words[0])
if n < m * word_len:
return []
target = Counter(words)
res = []
for start in range(word_len):
left = start
seen = Counter()
count = 0
for right in range(start, n - word_len + 1, word_len):
word = s[right:right + word_len]
if word in target:
seen[word] += 1
count += 1
while seen[word] > target[word]:
left_word = s[left:left + word_len]
seen[left_word] -= 1
left += word_len
count -= 1
if count == m:
res.append(left)
else:
seen.clear()
count = 0
left = right + word_len
return sorted(res)
Here is what you can do next.
Thank you so much. Share your invaluable thoughts in the comments section below.
Top comments (0)