Preparing for a coding interview? LeetCode is one of the best platforms to practice! In this guide, we will cover the most important LeetCode questions and their answers for 2025. Whether you are a beginner or an experienced coder, these questions will help you get ready for job interviews. We will explain each problem in a simple way so that even an 8th grader can understand. Letโs get started!
Contents
- 1 Leetcode Interview Questions and Answers
- 1.1 1. Two Sum (Easy)
- 1.2 2. Reverse a String (Easy)
- 1.3 3. Palindrome Number (Easy)
- 1.4 4. Merge Two Sorted Lists (Easy)
- 1.5 5. Valid Parentheses (Easy)
- 1.6 6. Remove Duplicates from Sorted Array (Easy)
- 1.7 7. Best Time to Buy and Sell Stock (Easy)
- 1.8 8. Search in Rotated Sorted Array (Medium)
- 1.9 9. Longest Substring Without Repeating Characters (Medium)
- 1.10 10. Subsets (Medium)
- 1.11 11. Coin Change (Medium)
- 1.12 12. Climbing Stairs (Easy)
- 1.13 13. Maximum Subarray (Kadaneโs Algorithm) (Easy)
- 1.14 14. Majority Element (Easy)
- 1.15 15. Binary Tree Inorder Traversal (Easy)
- 1.16 16. Symmetric Tree (Easy)
- 1.17 17. Linked List Cycle (Easy)
- 1.18 18. Product of Array Except Self (Medium)
- 1.19 19. Rotate Image (Matrix Rotation) (Medium)
- 1.20 20. Unique Paths (Medium)
- 1.21 21. Find the Missing Number (Easy)
- 1.22 22. Pow(x, n) (Medium)
- 1.23 23. Kth Largest Element in an Array (Medium)
- 1.24 24. Word Search (Medium)
- 1.25 25. Letter Combinations of a Phone Number (Medium)
- 1.26 26. Invert Binary Tree (Easy)
- 1.27 27. Lowest Common Ancestor of a Binary Tree (Medium)
- 1.28 28. Merge Intervals (Medium)
- 1.29 29. Insert Interval (Medium)
- 1.30 30. Validate Binary Search Tree (Medium)
- 1.31 31. Serialize and Deserialize Binary Tree (Hard)
- 1.32 32. Word Ladder (Medium)
- 1.33 33. N-Queens (Hard)
- 1.34 34. Combination Sum (Medium)
- 1.35 35. Permutations (Medium)
Leetcode Interview Questions and Answers
Friends These LeetCode Interview Questions (2025) along with answers and simple explanations cover various topics like arrays, strings, sorting, searching, recursion, and dynamic programming.
1. Two Sum (Easy)
Problem: Find two numbers in an array that add up to a target.
๐น Example: [2, 7, 11, 15], target = 9
โ Output: [0,1]
Solution:
def twoSum(nums, target):
hashmap = {}
for i, num in enumerate(nums):
diff = target - num
if diff in hashmap:
return [hashmap[diff], i]
hashmap[num] = i
return []
Explanation: We use a hash map to store numbers and their indices. If we find the complement (difference between target and number), we return their indices.
2. Reverse a String (Easy)
Problem: Reverse a given string in place.
๐น Example: "hello"
โ "olleh"
Solution:
def reverseString(s):
return s[::-1]
Explanation: The slicing method [::-1]
reverses the string.
3. Palindrome Number (Easy)
Problem: Check if a number is the same when reversed.
๐น Example: 121
โ True
, 123
โ False
Solution:
def isPalindrome(x):
return str(x) == str(x)[::-1]
Explanation: Convert the number to a string and compare it with its reverse.
4. Merge Two Sorted Lists (Easy)
Problem: Merge two sorted linked lists into one sorted list.
๐น Example: [1,3,5]
and [2,4,6]
โ [1,2,3,4,5,6]
Solution:
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def mergeTwoLists(l1, l2):
if not l1 or not l2:
return l1 or l2
if l1.val < l2.val:
l1.next = mergeTwoLists(l1.next, l2)
return l1
else:
l2.next = mergeTwoLists(l1, l2.next)
return l2
Explanation: Use recursion to merge the lists while keeping them sorted.
5. Valid Parentheses (Easy)
Problem: Check if a string of brackets is valid.
๐น Example: "({[]})"
โ True
, "({[})"
โ False
Solution:
def isValid(s):
stack = []
mapping = {')': '(', '}': '{', ']': '['}
for char in s:
if char in mapping:
top = stack.pop() if stack else '#'
if mapping[char] != top:
return False
else:
stack.append(char)
return not stack
Explanation: Use a stack to track opening brackets and check if they match the closing ones.
6. Remove Duplicates from Sorted Array (Easy)
Problem: Remove duplicates from a sorted array in-place.
๐น Example: [1,1,2]
โ [1,2]
Solution:
def removeDuplicates(nums):
if not nums:
return 0
i = 0
for j in range(1, len(nums)):
if nums[j] != nums[i]:
i += 1
nums[i] = nums[j]
return i + 1
Explanation: Use two pointers to overwrite duplicate values.
7. Best Time to Buy and Sell Stock (Easy)
Problem: Find the best time to buy and sell for max profit.
๐น Example: [7,1,5,3,6,4]
โ 5
Solution:
def maxProfit(prices):
min_price = float('inf')
max_profit = 0
for price in prices:
min_price = min(min_price, price)
max_profit = max(max_profit, price - min_price)
return max_profit
Explanation: Track the lowest price and max profit dynamically.
8. Search in Rotated Sorted Array (Medium)
Problem: Find a target in a rotated sorted array.
๐น Example: [4,5,6,7,0,1,2], target=0
โ 4
Solution:
def search(nums, target):
left, right = 0, len(nums) - 1
while left <= right:
mid = (left + right) // 2
if nums[mid] == target:
return mid
if nums[left] <= nums[mid]:
if nums[left] <= target < nums[mid]:
right = mid - 1
else:
left = mid + 1
else:
if nums[mid] < target <= nums[right]:
left = mid + 1
else:
right = mid - 1
return -1
Explanation: Use binary search while handling rotation cases.
9. Longest Substring Without Repeating Characters (Medium)
Problem: Find the longest unique character substring.
๐น Example: "abcabcbb"
โ 3
Solution:
def lengthOfLongestSubstring(s):
char_set = set()
left = max_length = 0
for right in range(len(s)):
while s[right] in char_set:
char_set.remove(s[left])
left += 1
char_set.add(s[right])
max_length = max(max_length, right - left + 1)
return max_length
Explanation: Use a sliding window technique.
10. Subsets (Medium)
Problem: Find all subsets of a given array.
๐น Example: [1,2,3]
โ [[],[1],[2],[3],[1,2],[1,3],[2,3],[1,2,3]]
Solution:
def subsets(nums):
res = [[]]
for num in nums:
res += [curr + [num] for curr in res]
return res
Explanation: Start with an empty list and add each number to all existing subsets.
11. Coin Change (Medium)
Problem: Find the fewest coins to make a given amount.
๐น Example: coins = [1,2,5], amount = 11
โ 3
Solution:
def coinChange(coins, amount):
dp = [float('inf')] * (amount + 1)
dp[0] = 0
for coin in coins:
for i in range(coin, amount + 1):
dp[i] = min(dp[i], dp[i - coin] + 1)
return dp[amount] if dp[amount] != float('inf') else -1
Explanation: Use dynamic programming to find the optimal solution.
12. Climbing Stairs (Easy)
Problem: You can climb 1 or 2 steps at a time. Find the number of ways to reach the top.
๐น Example: n = 3
โ 3
(Ways: [1,1,1], [1,2], [2,1]
)
Solution:
def climbStairs(n):
if n <= 2:
return n
a, b = 1, 2
for _ in range(3, n + 1):
a, b = b, a + b
return b
Explanation: It’s a Fibonacci-like problem where ways(n) = ways(n-1) + ways(n-2)
.
13. Maximum Subarray (Kadaneโs Algorithm) (Easy)
Problem: Find the contiguous subarray with the largest sum.
๐น Example: [-2,1,-3,4,-1,2,1,-5,4]
โ 6
Solution:
def maxSubArray(nums):
max_sum = cur_sum = nums[0]
for num in nums[1:]:
cur_sum = max(num, cur_sum + num)
max_sum = max(max_sum, cur_sum)
return max_sum
Explanation: Track the maximum subarray sum at each step.
14. Majority Element (Easy)
Problem: Find the element that appears more than n/2
times.
๐น Example: [3,2,3]
โ 3
Solution:
def majorityElement(nums):
count, candidate = 0, None
for num in nums:
if count == 0:
candidate = num
count += (1 if num == candidate else -1)
return candidate
Explanation: Uses Boyer-Moore Voting Algorithm.
15. Binary Tree Inorder Traversal (Easy)
Problem: Return the inorder traversal of a binary tree.
Solution:
def inorderTraversal(root):
res, stack = [], []
while root or stack:
while root:
stack.append(root)
root = root.left
root = stack.pop()
res.append(root.val)
root = root.right
return res
Explanation: Uses an iterative approach with a stack.
16. Symmetric Tree (Easy)
Problem: Check if a binary tree is a mirror of itself.
Solution:
def isSymmetric(root):
def isMirror(t1, t2):
if not t1 or not t2:
return t1 == t2
return (t1.val == t2.val and
isMirror(t1.left, t2.right) and
isMirror(t1.right, t2.left))
return isMirror(root, root)
Explanation: Recursively check if left and right subtrees are mirrors.
17. Linked List Cycle (Easy)
Problem: Detect if a linked list has a cycle.
Solution:
def hasCycle(head):
slow, fast = head, head
while fast and fast.next:
slow, fast = slow.next, fast.next.next
if slow == fast:
return True
return False
Explanation: Uses Floydโs Cycle Detection Algorithm (Tortoise & Hare).
18. Product of Array Except Self (Medium)
Problem: Return an array where each element is the product of all numbers except itself.
Solution:
def productExceptSelf(nums):
res = [1] * len(nums)
left = right = 1
for i in range(len(nums)):
res[i] *= left
left *= nums[i]
for i in range(len(nums) - 1, -1, -1):
res[i] *= right
right *= nums[i]
return res
Explanation: Use prefix & suffix multiplication to avoid division.
19. Rotate Image (Matrix Rotation) (Medium)
Problem: Rotate a NxN
matrix 90ยฐ clockwise.
Solution:
def rotate(matrix):
matrix.reverse()
for i in range(len(matrix)):
for j in range(i):
matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j]
Explanation: Reverse & Transpose for in-place rotation.
20. Unique Paths (Medium)
Problem: Find the number of ways to reach the bottom-right in a m x n
grid.
Solution:
import math
def uniquePaths(m, n):
return math.comb(m + n - 2, m - 1)
Explanation: Uses combinations formula (m+n-2 choose m-1).
21. Find the Missing Number (Easy)
Problem: Find the missing number in [0,1,2,3,...,n]
.
Solution:
def missingNumber(nums):
return sum(range(len(nums) + 1)) - sum(nums)
Explanation: Uses sum formula (n*(n+1))/2
.
22. Pow(x, n) (Medium)
Problem: Implement exponentiation function.
Solution:
def myPow(x, n):
if n == 0:
return 1
if n < 0:
x, n = 1 / x, -n
return x * myPow(x, n - 1) if n % 2 else myPow(x*x, n//2)
Explanation: Uses fast exponentiation (divide and conquer).
23. Kth Largest Element in an Array (Medium)
Problem: Find the k
th largest number in an array.
Solution:
import heapq
def findKthLargest(nums, k):
return heapq.nlargest(k, nums)[-1]
Explanation: Uses heap sorting for efficiency.
24. Word Search (Medium)
Problem: Check if a word exists in a m x n
board.
Solution:
def exist(board, word):
def dfs(i, j, idx):
if idx == len(word):
return True
if i < 0 or i >= len(board) or j < 0 or j >= len(board[0]) or board[i][j] != word[idx]:
return False
temp, board[i][j] = board[i][j], '#'
found = any(dfs(i + x, j + y, idx + 1) for x, y in [(0,1), (1,0), (0,-1), (-1,0)])
board[i][j] = temp
return found
return any(dfs(i, j, 0) for i in range(len(board)) for j in range(len(board[0])))
Explanation: Uses backtracking DFS to explore paths.
25. Letter Combinations of a Phone Number (Medium)
Problem: Return all possible letter combinations for a given phone number.
Solution:
from itertools import product
def letterCombinations(digits):
if not digits:
return []
mapping = {'2': 'abc', '3': 'def', '4': 'ghi', '5': 'jkl', '6': 'mno', '7': 'pqrs', '8': 'tuv', '9': 'wxyz'}
return [''.join(combo) for combo in product(*(mapping[d] for d in digits))]
Explanation: Uses cartesian product for combinations.
Below are 10 additional LeetCode interview questions (2025)โnumbered 26 to 35โwith solutions and simple explanations. These problems introduce more challenging topics including tree manipulation, intervals, and backtracking.
26. Invert Binary Tree (Easy)
Problem: Invert a binary tree (mirror image of the tree).
๐น Example:
Input: 4
/ \
2 7
Output: 4
/ \
7 2
Solution:
def invertTree(root):
if not root:
return None
root.left, root.right = invertTree(root.right), invertTree(root.left)
return root
Explanation: Swap the left and right child nodes recursively to invert the tree.
27. Lowest Common Ancestor of a Binary Tree (Medium)
Problem: Given a binary tree and two nodes, find their lowest common ancestor (LCA).
๐น Example:
For a tree and nodes p
and q
, return the deepest node that is an ancestor of both.
Solution:
def lowestCommonAncestor(root, p, q):
if not root or root == p or root == q:
return root
left = lowestCommonAncestor(root.left, p, q)
right = lowestCommonAncestor(root.right, p, q)
return root if left and right else left or right
Explanation: Recursively search left and right; if both sides return a node, then the current node is the LCA.
28. Merge Intervals (Medium)
Problem: Merge all overlapping intervals from a list.
๐น Example:[[1,3],[2,6],[8,10],[15,18]]
โ [[1,6],[8,10],[15,18]]
Solution:
def merge(intervals):
intervals.sort(key=lambda x: x[0])
merged = []
for interval in intervals:
if not merged or merged[-1][1] < interval[0]:
merged.append(interval)
else:
merged[-1][1] = max(merged[-1][1], interval[1])
return merged
Explanation: Sort intervals by start time then combine overlapping ones.
29. Insert Interval (Medium)
Problem: Insert a new interval into a list of non-overlapping intervals and merge if necessary.
๐น Example:intervals = [[1,3],[6,9]], newInterval = [2,5]
โ [[1,5],[6,9]]
Solution:
def insert(intervals, newInterval):
result = []
i = 0
while i < len(intervals) and intervals[i][1] < newInterval[0]:
result.append(intervals[i])
i += 1
while i < len(intervals) and intervals[i][0] <= newInterval[1]:
newInterval[0] = min(newInterval[0], intervals[i][0])
newInterval[1] = max(newInterval[1], intervals[i][1])
i += 1
result.append(newInterval)
result.extend(intervals[i:])
return result
Explanation: First add intervals before the new one, then merge overlapping intervals, and finally add the rest.
30. Validate Binary Search Tree (Medium)
Problem: Check if a binary tree is a valid binary search tree (BST).
๐น Example:
For a given binary tree, ensure that every nodeโs left subtree contains only values less than the nodeโs value and the right subtree only values greater.
Solution:
def isValidBST(root, low=float('-inf'), high=float('inf')):
if not root:
return True
if not (low < root.val < high):
return False
return isValidBST(root.left, low, root.val) and isValidBST(root.right, root.val, high)
Explanation: Recursively validate the BST property by setting valid ranges for each subtree.
31. Serialize and Deserialize Binary Tree (Hard)
Problem: Convert a binary tree to a string (serialization) and back to a tree (deserialization).
๐น Example:
A tree is converted to a string using pre-order traversal and then reconstructed.
Solution:
def serialize(root):
vals = []
def encode(node):
if node:
vals.append(str(node.val))
encode(node.left)
encode(node.right)
else:
vals.append('#')
encode(root)
return ' '.join(vals)
def deserialize(data):
vals = iter(data.split())
def decode():
val = next(vals)
if val == '#':
return None
node = TreeNode(int(val))
node.left = decode()
node.right = decode()
return node
return decode()
Explanation: Use pre-order traversal with a placeholder for null nodes; reverse the process during deserialization.
32. Word Ladder (Medium)
Problem: Find the length of the shortest transformation sequence from beginWord
to endWord
.
๐น Example:beginWord = "hit", endWord = "cog", wordList = ["hot","dot","dog","lot","log","cog"]
โ Output: 5
Solution:
from collections import deque
def ladderLength(beginWord, endWord, wordList):
wordSet = set(wordList)
if endWord not in wordSet:
return 0
queue = deque([(beginWord, 1)])
while queue:
word, steps = queue.popleft()
if word == endWord:
return steps
for i in range(len(word)):
for c in 'abcdefghijklmnopqrstuvwxyz':
nextWord = word[:i] + c + word[i+1:]
if nextWord in wordSet:
wordSet.remove(nextWord)
queue.append((nextWord, steps + 1))
return 0
Explanation: Use BFS to explore all possible single-letter transformations until reaching the end word.
33. N-Queens (Hard)
Problem: Place n
queens on an nรn
chessboard so that no two queens threaten each other.
๐น Example:
For n = 4
, return all valid arrangements.
Solution:
def solveNQueens(n):
solutions = []
board = [-1] * n
def isValid(row, col):
for i in range(row):
if board[i] == col or abs(board[i] - col) == row - i:
return False
return True
def backtrack(row):
if row == n:
sol = []
for i in board:
line = ['.'] * n
line[i] = 'Q'
sol.append(''.join(line))
solutions.append(sol)
return
for col in range(n):
if isValid(row, col):
board[row] = col
backtrack(row + 1)
board[row] = -1
backtrack(0)
return solutions
Explanation: Use backtracking to try each column and check for valid queen placement.
34. Combination Sum (Medium)
Problem: Find all unique combinations where numbers sum to a target.
๐น Example:
For candidates = [2,3,6,7]
and target = 7
, output: [[7],[2,2,3]]
Solution:
def combinationSum(candidates, target):
result = []
def backtrack(remain, combo, start):
if remain == 0:
result.append(list(combo))
return
elif remain < 0:
return
for i in range(start, len(candidates)):
combo.append(candidates[i])
backtrack(remain - candidates[i], combo, i)
combo.pop()
backtrack(target, [], 0)
return result
Explanation: Use backtracking to build combinations while subtracting candidates until the target is met.
35. Permutations (Medium)
Problem: Return all possible permutations of a given list.
๐น Example:
For nums = [1,2,3]
, output all 6 permutations.
Solution:
def permute(nums):
result = []
def backtrack(first=0):
if first == len(nums):
result.append(nums[:])
for i in range(first, len(nums)):
nums[first], nums[i] = nums[i], nums[first]
backtrack(first + 1)
nums[first], nums[i] = nums[i], nums[first]
backtrack()
return result
Explanation: Use backtracking with swapping to generate all permutations.