I just posted a few days ago the first 30 LeetCode problems you can solve with Python code. Here is the post.
If you have already done this, here are the next 30 problems.
The next 30 problems of https://leetcode.com/problemset/ (default view, problems 31–60), 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 |
|---|---|---|
| 31 | Next Permutation | Medium |
| 32 | Longest Valid Parentheses | Hard |
| 33 | Search in Rotated Sorted Array | Medium |
| 34 | Find First and Last Position of Element in Sorted Array | Medium |
| 35 | Search Insert Position | Easy |
| 36 | Valid Sudoku | Medium |
| 37 | Sudoku Solver | Hard |
| 38 | Count and Say | Medium |
| 39 | Combination Sum | Medium |
| 40 | Combination Sum II | Medium |
| 41 | First Missing Positive | Hard |
| 42 | Trapping Rain Water | Hard |
| 43 | Multiply Strings | Medium |
| 44 | Wildcard Matching | Hard |
| 45 | Jump Game II | Medium |
| 46 | Permutations | Medium |
| 47 | Permutations II | Medium |
| 48 | Rotate Image | Medium |
| 49 | Group Anagrams | Medium |
| 50 | Pow(x, n) | Medium |
| 51 | N-Queens | Hard |
| 52 | N-Queens II | Hard |
| 53 | Maximum Subarray | Medium |
| 54 | Spiral Matrix | Medium |
| 55 | Jump Game | Medium |
| 56 | Merge Intervals | Medium |
| 57 | Insert Interval | Medium |
| 58 | Length of Last Word | Easy |
| 59 | Spiral Matrix II | Medium |
| 60 | Permutation Sequence | Hard |
31. Next Permutation (Medium)
https://leetcode.com/problems/next-permutation
class Solution:
def nextPermutation(self, nums: List[int]) -> None:
n = len(nums)
i = n - 2
while i >= 0 and nums[i] >= nums[i + 1]:
i -= 1
if i >= 0:
j = n - 1
while nums[j] <= nums[i]:
j -= 1
nums[i], nums[j] = nums[j], nums[i]
nums[i + 1:] = reversed(nums[i + 1:])
32. Longest Valid Parentheses (Hard)
https://leetcode.com/problems/longest-valid-parentheses
class Solution:
def longestValidParentheses(self, s: str) -> int:
stack = [-1]
best = 0
for i, ch in enumerate(s):
if ch == "(":
stack.append(i)
else:
stack.pop()
if not stack:
stack.append(i)
else:
best = max(best, i - stack[-1])
return best
33. Search in Rotated Sorted Array (Medium)
https://leetcode.com/problems/search-in-rotated-sorted-array
class Solution:
def search(self, nums: List[int], target: int) -> int:
lo, hi = 0, len(nums) - 1
while lo <= hi:
mid = (lo + hi) // 2
if nums[mid] == target:
return mid
if nums[lo] <= nums[mid]:
if nums[lo] <= target < nums[mid]:
hi = mid - 1
else:
lo = mid + 1
else:
if nums[mid] < target <= nums[hi]:
lo = mid + 1
else:
hi = mid - 1
return -1
34. Find First and Last Position of Element in Sorted Array (Medium)
https://leetcode.com/problems/find-first-and-last-position-of-element-in-sorted-array
class Solution:
def searchRange(self, nums: List[int], target: int) -> List[int]:
def lower_bound(t):
lo, hi = 0, len(nums)
while lo < hi:
mid = (lo + hi) // 2
if nums[mid] < t:
lo = mid + 1
else:
hi = mid
return lo
first = lower_bound(target)
if first == len(nums) or nums[first] != target:
return [-1, -1]
last = lower_bound(target + 1) - 1
return [first, last]
35. Search Insert Position (Easy)
https://leetcode.com/problems/search-insert-position
class Solution:
def searchInsert(self, nums: List[int], target: int) -> int:
lo, hi = 0, len(nums)
while lo < hi:
mid = (lo + hi) // 2
if nums[mid] < target:
lo = mid + 1
else:
hi = mid
return lo
36. Valid Sudoku (Medium)
https://leetcode.com/problems/valid-sudoku
class Solution:
def isValidSudoku(self, board: List[List[str]]) -> bool:
rows = [set() for _ in range(9)]
cols = [set() for _ in range(9)]
boxes = [set() for _ in range(9)]
for r in range(9):
for c in range(9):
v = board[r][c]
if v == ".":
continue
b = (r // 3) * 3 + c // 3
if v in rows[r] or v in cols[c] or v in boxes[b]:
return False
rows[r].add(v)
cols[c].add(v)
boxes[b].add(v)
return True
37. Sudoku Solver (Hard)
https://leetcode.com/problems/sudoku-solver
class Solution:
def solveSudoku(self, board: List[List[str]]) -> None:
rows = [0] * 9
cols = [0] * 9
boxes = [0] * 9
empties = []
for r in range(9):
for c in range(9):
v = board[r][c]
if v == ".":
empties.append([r, c])
else:
bit = 1 << int(v)
rows[r] |= bit
cols[c] |= bit
boxes[(r // 3) * 3 + c // 3] |= bit
digits = "0123456789"
k = len(empties)
def backtrack(i):
if i == k:
return True
# MRV: pick the remaining cell with the fewest candidates
best = -1
best_free = 0
best_cnt = 10
for j in range(i, k):
r, c = empties[j]
free = ~(rows[r] | cols[c] | boxes[(r // 3) * 3 + c // 3]) & 0x3FE
cnt = free.bit_count()
if cnt == 0:
return False
if cnt < best_cnt:
best, best_free, best_cnt = j, free, cnt
if cnt == 1:
break
empties[i], empties[best] = empties[best], empties[i]
r, c = empties[i]
b = (r // 3) * 3 + c // 3
free = best_free
while free:
bit = free & -free
free -= bit
board[r][c] = digits[bit.bit_length() - 1]
rows[r] |= bit
cols[c] |= bit
boxes[b] |= bit
if backtrack(i + 1):
return True
rows[r] ^= bit
cols[c] ^= bit
boxes[b] ^= bit
board[r][c] = "."
return False
backtrack(0)
38. Count and Say (Medium)
https://leetcode.com/problems/count-and-say
class Solution:
def countAndSay(self, n: int) -> str:
s = "1"
for _ in range(n - 1):
out = []
i = 0
while i < len(s):
j = i
while j < len(s) and s[j] == s[i]:
j += 1
out.append(str(j - i))
out.append(s[i])
i = j
s = "".join(out)
return s
39. Combination Sum (Medium)
https://leetcode.com/problems/combination-sum
class Solution:
def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:
res = []
candidates.sort()
def backtrack(start, cur, remaining):
if remaining == 0:
res.append(cur[:])
return
for i in range(start, len(candidates)):
if candidates[i] > remaining:
break
cur.append(candidates[i])
backtrack(i, cur, remaining - candidates[i])
cur.pop()
backtrack(0, [], target)
return res
40. Combination Sum II (Medium)
https://leetcode.com/problems/combination-sum-ii
class Solution:
def combinationSum2(self, candidates: List[int], target: int) -> List[List[int]]:
res = []
candidates.sort()
def backtrack(start, cur, remaining):
if remaining == 0:
res.append(cur[:])
return
for i in range(start, len(candidates)):
if i > start and candidates[i] == candidates[i - 1]:
continue
if candidates[i] > remaining:
break
cur.append(candidates[i])
backtrack(i + 1, cur, remaining - candidates[i])
cur.pop()
backtrack(0, [], target)
return res
41. First Missing Positive (Hard)
https://leetcode.com/problems/first-missing-positive
class Solution:
def firstMissingPositive(self, nums: List[int]) -> int:
n = len(nums)
for i in range(n):
while nums[i] != i + 1 and 1 <= nums[i] <= n and nums[nums[i] - 1] != nums[i]:
j = nums[i] - 1
nums[i], nums[j] = nums[j], nums[i]
for i in range(n):
if nums[i] != i + 1:
return i + 1
return n + 1
42. Trapping Rain Water (Hard)
https://leetcode.com/problems/trapping-rain-water
class Solution:
def trap(self, height: List[int]) -> int:
lo, hi = 0, len(height) - 1
left_max = right_max = 0
water = 0
while lo < hi:
if height[lo] < height[hi]:
if height[lo] >= left_max:
left_max = height[lo]
else:
water += left_max - height[lo]
lo += 1
else:
if height[hi] >= right_max:
right_max = height[hi]
else:
water += right_max - height[hi]
hi -= 1
return water
43. Multiply Strings (Medium)
https://leetcode.com/problems/multiply-strings
class Solution:
def multiply(self, num1: str, num2: str) -> str:
if num1 == "0" or num2 == "0":
return "0"
m, n = len(num1), len(num2)
pos = [0] * (m + n)
for i in range(m - 1, -1, -1):
for j in range(n - 1, -1, -1):
mul = (ord(num1[i]) - 48) * (ord(num2[j]) - 48)
p1, p2 = i + j, i + j + 1
total = mul + pos[p2]
pos[p2] = total % 10
pos[p1] += total // 10
return "".join(map(str, pos)).lstrip("0") or "0"
44. Wildcard Matching (Hard)
https://leetcode.com/problems/wildcard-matching
class Solution:
def isMatch(self, s: str, p: str) -> bool:
m, n = len(s), len(p)
dp = [False] * (n + 1)
dp[0] = True
for j in range(1, n + 1):
if p[j - 1] == "*":
dp[j] = dp[j - 1]
else:
break
for i in range(1, m + 1):
prev = dp[0]
dp[0] = False
for j in range(1, n + 1):
cur = dp[j]
if p[j - 1] == "*":
dp[j] = dp[j] or dp[j - 1]
elif p[j - 1] == "?" or p[j - 1] == s[i - 1]:
dp[j] = prev
else:
dp[j] = False
prev = cur
return dp[n]
45. Jump Game II (Medium)
https://leetcode.com/problems/jump-game-ii
class Solution:
def jump(self, nums: List[int]) -> int:
jumps = 0
cur_end = 0
farthest = 0
for i in range(len(nums) - 1):
farthest = max(farthest, i + nums[i])
if i == cur_end:
jumps += 1
cur_end = farthest
return jumps
46. Permutations (Medium)
https://leetcode.com/problems/permutations
class Solution:
def permute(self, nums: List[int]) -> List[List[int]]:
res = []
n = len(nums)
def backtrack(start, path):
if start == n:
res.append(path[:])
return
for i in range(start, n):
nums[i], nums[start] = nums[start], nums[i]
path.append(nums[start])
backtrack(start + 1, path)
path.pop()
nums[i], nums[start] = nums[start], nums[i]
backtrack(0, [])
return res
47. Permutations II (Medium)
https://leetcode.com/problems/permutations-ii
class Solution:
def permuteUnique(self, nums: List[int]) -> List[List[int]]:
nums.sort()
res = []
used = [False] * len(nums)
def backtrack(path):
if len(path) == len(nums):
res.append(path[:])
return
for i in range(len(nums)):
if used[i]:
continue
if i > 0 and nums[i] == nums[i - 1] and not used[i - 1]:
continue
used[i] = True
path.append(nums[i])
backtrack(path)
path.pop()
used[i] = False
backtrack([])
return res
48. Rotate Image (Medium)
https://leetcode.com/problems/rotate-image
class Solution:
def rotate(self, matrix: List[List[int]]) -> None:
n = len(matrix)
for i in range(n):
for j in range(i + 1, n):
matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j]
for row in matrix:
row.reverse()
49. Group Anagrams (Medium)
https://leetcode.com/problems/group-anagrams
class Solution:
def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
groups = {}
for s in strs:
key = "".join(sorted(s))
if key not in groups:
groups[key] = []
groups[key].append(s)
return list(groups.values())
50. Pow(x, n) (Medium)
https://leetcode.com/problems/powx-n
class Solution:
def myPow(self, x: float, n: int) -> float:
if n == 0:
return 1.0
if n < 0:
x = 1.0 / x
n = -n
res = 1.0
while n:
if n & 1:
res *= x
x *= x
n >>= 1
return res
51. N-Queens (Hard)
https://leetcode.com/problems/n-queens
class Solution:
def solveNQueens(self, n: int) -> List[List[str]]:
res = []
board = [["."] * n for _ in range(n)]
cols = set()
diag1 = set()
diag2 = set()
def backtrack(r):
if r == n:
res.append(["".join(row) for row in board])
return
for c in range(n):
if c in cols or (r - c) in diag1 or (r + c) in diag2:
continue
board[r][c] = "Q"
cols.add(c)
diag1.add(r - c)
diag2.add(r + c)
backtrack(r + 1)
board[r][c] = "."
cols.remove(c)
diag1.remove(r - c)
diag2.remove(r + c)
backtrack(0)
return res
52. N-Queens II (Hard)
https://leetcode.com/problems/n-queens-ii
class Solution:
def totalNQueens(self, n: int) -> int:
count = 0
cols = set()
diag1 = set()
diag2 = set()
def backtrack(r):
nonlocal count
if r == n:
count += 1
return
for c in range(n):
if c in cols or (r - c) in diag1 or (r + c) in diag2:
continue
cols.add(c)
diag1.add(r - c)
diag2.add(r + c)
backtrack(r + 1)
cols.remove(c)
diag1.remove(r - c)
diag2.remove(r + c)
backtrack(0)
return count
53. Maximum Subarray (Medium)
https://leetcode.com/problems/maximum-subarray
class Solution:
def maxSubArray(self, nums: List[int]) -> int:
best = cur = nums[0]
for x in nums[1:]:
cur = max(x, cur + x)
best = max(best, cur)
return best
54. Spiral Matrix (Medium)
https://leetcode.com/problems/spiral-matrix
class Solution:
def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
res = []
if not matrix:
return res
top, bottom = 0, len(matrix) - 1
left, right = 0, len(matrix[0]) - 1
while top <= bottom and left <= right:
for c in range(left, right + 1):
res.append(matrix[top][c])
top += 1
for r in range(top, bottom + 1):
res.append(matrix[r][right])
right -= 1
if top <= bottom:
for c in range(right, left - 1, -1):
res.append(matrix[bottom][c])
bottom -= 1
if left <= right:
for r in range(bottom, top - 1, -1):
res.append(matrix[r][left])
left += 1
return res
55. Jump Game (Medium)
https://leetcode.com/problems/jump-game
class Solution:
def canJump(self, nums: List[int]) -> bool:
farthest = 0
for i, x in enumerate(nums):
if i > farthest:
return False
farthest = max(farthest, i + x)
return True
56. Merge Intervals (Medium)
https://leetcode.com/problems/merge-intervals
class Solution:
def merge(self, intervals: List[List[int]]) -> List[List[int]]:
intervals.sort()
res = []
for start, end in intervals:
if res and start <= res[-1][1]:
res[-1][1] = max(res[-1][1], end)
else:
res.append([start, end])
return res
57. Insert Interval (Medium)
https://leetcode.com/problems/insert-interval
class Solution:
def insert(self, intervals: List[List[int]], newInterval: List[int]) -> List[List[int]]:
res = []
i = 0
n = len(intervals)
while i < n and intervals[i][1] < newInterval[0]:
res.append(intervals[i])
i += 1
while i < n and intervals[i][0] <= newInterval[1]:
newInterval = [min(newInterval[0], intervals[i][0]), max(newInterval[1], intervals[i][1])]
i += 1
res.append(newInterval)
while i < n:
res.append(intervals[i])
i += 1
return res
58. Length of Last Word (Easy)
https://leetcode.com/problems/length-of-last-word
class Solution:
def lengthOfLastWord(self, s: str) -> int:
s = s.rstrip()
if not s:
return 0
return len(s) - s.rfind(" ") - 1
59. Spiral Matrix II (Medium)
https://leetcode.com/problems/spiral-matrix-ii
class Solution:
def generateMatrix(self, n: int) -> List[List[int]]:
matrix = [[0] * n for _ in range(n)]
top, bottom = 0, n - 1
left, right = 0, n - 1
val = 1
while top <= bottom and left <= right:
for c in range(left, right + 1):
matrix[top][c] = val
val += 1
top += 1
for r in range(top, bottom + 1):
matrix[r][right] = val
val += 1
right -= 1
if top <= bottom:
for c in range(right, left - 1, -1):
matrix[bottom][c] = val
val += 1
bottom -= 1
if left <= right:
for r in range(bottom, top - 1, -1):
matrix[r][left] = val
val += 1
left += 1
return matrix
60. Permutation Sequence (Hard)
https://leetcode.com/problems/permutation-sequence
class Solution:
def getPermutation(self, n: int, k: int) -> str:
digits = [str(d) for d in range(1, n + 1)]
fact = [1] * (n + 1)
for i in range(2, n + 1):
fact[i] = fact[i - 1] * i
k -= 1
res = []
for i in range(n, 0, -1):
idx = k // fact[i - 1]
res.append(digits.pop(idx))
k %= fact[i - 1]
return "".join(res)
Here's what you might be interested in next.
Thank you so much for reading this. If you have read this far, please share your valuable thoughts in the comments below.
Top comments (0)